Sancy P Devassy
Sancy P Devassy

Reputation: 41

Restart animation of previous activity when onBackPressed()

I have a GridView with an animation. When we launch the activity the animation works, from there if we go to another activity, I need the animation to restart again as the same way as when it was launched. Now when the Back button is pressed, it goes to the previous activity but there is no animation for the aforementioned GridView. Here is the code:

CustomGrid adapter = new CustomGrid(Grids.this, web, imageId);
grid = (GridView) findViewById(R.id.grid);
grid.setAdapter(adapter);
Animation animation = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.grid_item_anim);
controller = new GridLayoutAnimationController(animation, .2f, .2f);
grid.setLayoutAnimation(controller);

Upvotes: 0

Views: 353

Answers (2)

justussimon91
justussimon91

Reputation: 121

From your description, I assume that you put your code above into the onCreate() method of your activity. Try putting it into onResume() instead, which is called everytime an activity is resumed (navigated back to, in your case), as opposed to onCreate().

Upvotes: 0

Rucha Bhatt Joshi
Rucha Bhatt Joshi

Reputation: 832

Go through this link ActivityLifeCycle

It simply because i'm assuming you wrote your code on onCreate(); when you start activity it calls onCreate() only one time when you switch your activity and come back, your state is changed to onResume() so your code of animation stop working.

you need to write your code in onResume() Method which call when you launch activity and also whenever you come back to your activity.

When the Activity first time loads the events are called as below:

onCreate()
onStart()
onResume()

When switch the activity

onPause()

When back to activity

onResume()

Note: One thing to be aware of is that onResume() gets called also when a configuration change happens. Putting the code in onResume() will cause the animation tobe played again when you rotate the device. You might want to avoid this or not depending on your requirements.

Upvotes: 2

Related Questions