Aneri Shah Aneri Shah - 2 months ago 12
Android Question

How do I change the activity after animation ends? Animation listener doesnt seem to be working

I want to start an animation as soon as the activity is launched. And as soon as the animation ends, I want to start another activity.So I searched a lot and everyone recommended to use onAnimationEnd(). However, on running the code, no new activity is displayed after the animation ends. Can someone point out my error?

Here is my MainActivity.java

public class MainActivity extends AppCompatActivity implements Animation.AnimationListener {
TextView ticTacToe;
Animation animation;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ticTacToe = (TextView) findViewById(R.id.tictactoe);
//bounce is the xml animation file
animation= AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.bounce);
}

@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus)
ticTacToe.startAnimation(animation);
}

@Override
public void onAnimationStart(Animation animation) {

}

@Override
public void onAnimationEnd(Animation animation) {
Intent intent = new Intent(this,Main2Activity.class);
startActivity(intent);
}

@Override
public void onAnimationRepeat(Animation animation) {

}
}

Answer

Do this in your onWindowFocusChanged, because your animation starts when your current window get focus but the listener is still not attached to your animation

    animation.setAnimationListener(new AnimationListener() {
        public void onAnimationStart(Animation animation) {}
        public void onAnimationRepeat(Animation animation) {}
        public void onAnimationEnd(Animation animation) {
Intent intent = new Intent(MainActivity.this,Main2Activity.class);
startActivity(intent);
        }
    }    

    ticTacToe.startAnimation(animation)

Or you can also do this in oncreate

animation.setAnimationListener(this);