Подтвердить что ты не робот

Слайд справа налево Android Animations

Эй, я работаю над проектом Android, который требует анимации слайдов в Android WebView. Когда пользователь щелкает слева направо, он переходит на новую страницу, и когда он делает это справа налево, он перемещается на предыдущую страницу. Но у Android есть только два перехода для этого: slide_out_right и slide_in_left. После их использования левая и правая скользящие работы безупречны, а другая выглядит странно (противоположно).

Любые решения для него. Я хочу, чтобы анимация slide_out_left была более точной.

4b9b3361

Ответ 1

Прочитайте сообщение в блоге с примером анимации перехода, я включил следующий код:

Вызывающая активность

package com.as400samplecode;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener{

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  Button nextActivity = (Button) findViewById(R.id.nextActivity);
  nextActivity.setOnClickListener(this);

 }

 public void onClick(View v) {

  switch (v.getId()) {
  case R.id.nextActivity:
   Intent nextActivity = new Intent(this,NextActivity.class);
   startActivity(nextActivity);
   //push from bottom to top
   overridePendingTransition(R.anim.push_up_in, R.anim.push_up_out);
   //slide from right to left
   //overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
   break;

   // More buttons go here (if any) ...

  }
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.activity_main, menu);
  return true;
 }

}

Ресурс компоновки для вызывающей активности

<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
 android:layout_height="match_parent" tools:context=".MainActivity"
 android:background="@color/ivory"> 
 <Button android:id="@+id/nextActivity" android:layout_width="match_parent"
  android:layout_height="wrap_content" android:layout_alignParentLeft="true"
  android:layout_alignParentTop="true" android:layout_marginTop="15dp"
  android:text="Go to Next Activity" /> 
</RelativeLayout>

Вызываемая активность

package com.as400samplecode;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class NextActivity extends Activity implements OnClickListener{

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_next);

        Button previousActivity = (Button) findViewById(R.id.previousActivity);
        previousActivity.setOnClickListener(this);

    }

 public void onClick(View v) {

  switch (v.getId()) {
  case R.id.previousActivity:
   finish();
   //push from top to bottom
   overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
   //slide from left to right
   //overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
   break;

   // More buttons go here (if any) ...

  }
 }


}

Ресурс компоновки для вызываемой активности

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
 android:layout_height="match_parent" tools:context=".NextActivity"
 android:background="@color/khaki">

 <Button android:id="@+id/previousActivity" android:layout_width="match_parent"
  android:layout_height="wrap_content" android:layout_alignParentLeft="true"
  android:layout_alignParentTop="true" android:layout_marginTop="15dp"
  android:text="Go to Previous Activity" />

</RelativeLayout>

Анимационный ресурс - push_down_in.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
 <translate android:fromYDelta="-100%p" android:toYDelta="0" android:duration="5000"/>
 <alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="5000" />
</set>

Анимационный ресурс - push_down_out.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
 <translate android:fromYDelta="0" android:toYDelta="100%p" android:duration="5000" />
 <alpha android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="5000" />
</set>

Анимационный ресурс - push_up_in.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
 <translate android:fromYDelta="100%p" android:toYDelta="0" android:duration="5000"/>
 <alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="5000" />
</set>

Анимационный ресурс - push_up_out.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
 <translate android:fromYDelta="0" android:toYDelta="-100%p" android:duration="5000"/>
 <alpha android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="5000" />
</set>

Ресурс анимации - slide_in_left.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:shareInterpolator="false" >
    <translate android:duration="5000" android:fromXDelta="-100%" android:toXDelta="0%"/>
    <alpha android:duration="5000" android:fromAlpha="0.0" android:toAlpha="1.0" />
</set>

Ресурс анимации - slide_in_right.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:shareInterpolator="false" >
    <translate android:duration="5000" android:fromXDelta="100%" android:toXDelta="0%" />
    <alpha android:duration="5000" android:fromAlpha="0.0" android:toAlpha="1.0" />
</set>

Ресурс анимации - slide_out_left.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:shareInterpolator="false" >
    <translate android:duration="5000" android:fromXDelta="0%" android:toXDelta="-100%"/>
    <alpha android:duration="5000" android:fromAlpha="1.0" android:toAlpha="0.0" />
</set>

Ресурс анимации - slide_out_right.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:shareInterpolator="false" >
    <translate android:duration="5000" android:fromXDelta="0%" android:toXDelta="100%"/>
    <alpha android:duration="5000" android:fromAlpha="1.0" android:toAlpha="0.0" />
</set>

Ответ 2

Вы можете сделать свой собственный стиль анимации в виде XML файла, подобного этому (поместите его в папку с анимацией):

слева направо:

  <set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="false">
        <translate android:fromXDelta="-100%" android:toXDelta="0%"
         android:fromYDelta="0%" android:toYDelta="0%"
         android:duration="500"/>
  </set>

справа налево:

    <set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="false">
     <translate
        android:fromXDelta="0%" android:toXDelta="100%"
        android:fromYDelta="0%" android:toYDelta="0%"
        android:duration="500" />
   </set>

Здесь вы можете установить свои собственные значения на длительность, возможно, это зависит от модели телефона, как будет выглядеть анимация, попробуйте некоторые значения, если это выглядит не очень хорошо.

а затем вы можете вызвать его в своей деятельности:

     Intent animActivity = new Intent(this,YourStartAfterAnimActivity.class);
      startActivity(nextActivity);

      overridePendingTransition(R.anim.your_left_to_right, R.anim.your_right_to_left);

Ответ 3

Для скользящей активности (старого и нового) в том же направлении:

left_in.xml

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="300"
    android:fromXDelta="-100%"
    android:toXDelta="0%"
    android:interpolator="@android:anim/decelerate_interpolator"
     />

right_in.xml

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="300"
    android:fromXDelta="100%"
    android:toXDelta="0%"
    android:interpolator="@android:anim/decelerate_interpolator"
     />

left_out.xml

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="300"
    android:fromXDelta="0%"
    android:interpolator="@android:anim/decelerate_interpolator"
    android:toXDelta="-100%" />

right_out.xml

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="300"
    android:fromXDelta="0%"
    android:interpolator="@android:anim/decelerate_interpolator"
    android:toXDelta="100%" />

переход startActivity:

overridePendingTransition(R.anim.right_in, R.anim.left_out);

onBackPressed переход:

overridePendingTransition(R.anim.left_in, R.anim.right_out);

Ответ 4

Посмотрите эту ссылку.. вы можете увидеть так много видов анимаций здесь, просто скопируйте xml в папку res/anim и используйте его, как показано ниже.

listView.setAnimation(AnimationUtils.loadAnimation(MainActivity.this,R.anim.slide_in_right));

Анимационные списки

Ответ 5

Пример GIF

Самый простой способ, который я нашел, - использовать Activity Transitions, это действительно легко

Переопределить метод onCreate в активности, которую вы хотите запустить с анимацией:

@Override
  protected void onCreate(Bundle savedInstanceState) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
      Slide slide = new Slide();
      slide.setSlideEdge(Gravity.RIGHT);

      getWindow().setEnterTransition(slide);
    }
    super.onCreate(savedInstanceState);
  }

Затем запустите его с помощью переходов (вместо activity.startActivity(context)):

activity.startActivity(starter, ActivityOptions.makeSceneTransitionAnimation(activity).toBundle());

Для закрытия активности с использованием анимации, используя this.finish(), используйте код ниже:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
      getActivity().finishAfterTransition();
    } else getActivity().finish();

Для получения дополнительной информации см. ссылки ниже:

Ответ 6

Вы можете создавать свои собственные анимации. Например, создайте xml файл в res/anim, как этот

<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android"
     android:interpolator="@android:anim/linear_interpolator">
    <translate
            android:fromXDelta="100%p"
            android:toXDelta="0"
            android:startOffset="0"
            android:duration="500"
            /> </set>

Затем переопределите анимацию в выбранной деятельности:

   overridePendingTransition(R.anim.animationIN, R.anim.animationOUT);

Ответ 7

Анимация новой страницы с левой стороны слева.

<set xmlns:android="http://schemas.android.com/apk/res/android"
 android:shareInterpolator="false">
 <translate
    android:fromXDelta="0%" android:toXDelta="800%"
    android:fromYDelta="0%" android:toYDelta="0%"
    android:duration="600" />