I have a MainActivity
(which has launchMode=singleTop) from which I go to other activities, For eg B
and C
. Now, I want to navigate back to MainActivity
on some button click in B
and C
. And also I want transition animation.
Here is the code
CODE 1
Intent intent=new Intent(this,MainActivity.class);
Bundle animation= ActivityOptions.makeCustomAnimation(getApplicationContext(), R.animator.translate_left_to_right, R.animator.translate_source_left_to_right).toBundle();
startActivity(intent,animation);
finish();
The above code works fine, EXCEPT the fact that a new instance of MainActivity
is created on top of the old one! I don't want that to happen. So, after a bit of research I tried the below code
CODE 2
Intent intent=new Intent(this,ListingActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Bundle animation= ActivityOptions.makeCustomAnimation(getApplicationContext(), R.animator.translate_left_to_right, R.animator.translate_source_left_to_right).toBundle();
startActivity(intent,animation);
finish();
This code seemed to remove the problem of creating a new instance of the activity as the flag FLAG_ACTIVITY_CLEAR_TOP
took care of it. BUT, now the transition animation does not seem to work!
Does the flag FLAG_ACTIVITY_CLEAR_TOP
not allow any animation? What is the solution to my problem? I need both animation transition and also that a new instance of the MainActivity
should NOT be created.
EDIT
This seems to do the trick as suggested by David Wasser.
Intent intent=new Intent(this,ListingActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
finish();
overridePendingTransition(R.animator.translate_left_to_right,R.animator.translate_source_left_to_right);
BUT the animation is not smooth. There is a glitch in the animation. I think that is because the activity (B or C) gets destroyed before the animation is complete. I am not sure though
Posting the animations files
translate_left_to_right.xml
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="-100%p"
android:toXDelta="0%p"
android:duration="400"/>
translate_right_to_left.xml
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="100%p"
android:toXDelta="0"
android:duration="400"/>
translate_source_left_to_right.xml
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="0%p"
android:toXDelta="50%p"
android:duration="400"/>
translate_source_right_to_left.xml
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="0"
android:toXDelta="-50%p"
android:duration="400"/>