user3616949
user3616949

Reputation: 53

Use animation when changing activity

I would like to use a right-to-left sliding animation when transitioning between two activities. So far, I have set up a command to pass to the next activity.

public void advancenext (View view) {
        Intent intent = new Intent(Prompt1.this, Prompt2.class);
        Prompt1.this.startActivity(intent);
}

However, I am having trouble incorporating the animation into this code. This is what I have so far for the translation animation

Animation set = new AnimationSet(true);
Animation animation = new AlphaAnimation(0.0f, 1.0f);
animation.setDuration(100);
  set.addAnimation(animation);

  animation = new TranslateAnimation(
      Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f,
      Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF, 0.0f
  );
  animation.setDuration(500);
  set.addAnimation(animation);

  LayoutAnimationController controller =
      new LayoutAnimationController(set, 0.25f);

How would I go about combining the animation information with the activity change?

Thanks in advance

Upvotes: 1

Views: 1675

Answers (1)

matiash
matiash

Reputation: 55380

To set up an activity entrance animation, you must create a tween animation (involving alpha, scale, translate, &c) in the res\anim folder and then call overridePendingTransition() just after invoking startActivity().

For example, you could get an "activity enters from right and pushes the previous one out" effect (which if I understood correctly is what you need) with these animation files:

push_left_exit.xml

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

push_left_enter.xml

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

It's advisable to set up a "reverse" animation when finishing the activity, so effect when the back button is pressed is coherent with the entrance.

Upvotes: 4

Related Questions