Activity slide animation only works when back button is pressed

374 views Asked by At

Im trying to add a sliding animation when entering and exiting an activity but it only works when the phones back button is pressed. When pressing the up button in the toolbar or a separate button it doesn't work.

I tried adding the overridePendingTransition(R.anim.no_anim, R.anim.slide_out_right); line to the onPause() method as well as the finish() method and the buttons OnClick method but it doesn't work :/

no_anim.xml:

<?xml version="1.0" encoding="utf-8"?>

<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="0"
        android:fromXDelta="0"
        android:toXDelta="0" />
</set>

slide_out_right.xml:

<?xml version="1.0" encoding="utf-8"?>

<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="@android:integer/config_longAnimTime"
        android:fromXDelta="0"
        android:toXDelta="100%p" />
</set>

Java:

public void button(View view) {
    Intent intent = new Intent(this, MainActivity.class);
    startActivity(intent);
    overridePendingTransition(R.anim.no_anim, R.anim.slide_out_right);
}

@Override
public void finish(){
    super.finish();
    overridePendingTransition(R.anim.no_anim, R.anim.slide_out_right);
}

@Override
protected void onPause() {
    super.onPause();
    overridePendingTransition(R.anim.no_anim, R.anim.slide_out_right);
}
2

There are 2 answers

1
Saurav Ghimire On

You can call onBackPressed() when pressing the up button in the toolbar

0
Gourav On

Set toolbar Navigation click listener:

toolbar.setNavigationOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        finish(); //close activity
        overridePendingTransition(R.anim.your_anim, R.anim.your_anim);
    }
});

This will surely work!