Search code examples
javaandroidandroid-actionbar

How to add a listener for the up button in ActionBar on Android?


I added the up button in the action bar of my android activity in this way:

Activity:

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

Manifest:

android:parentActivityName=".MenuActivity">

It work fine but now i want to add a transition effect between activities. This transition work well:

Intent intent = new Intent(getApplicationContext(), MenuActivity.class); startActivity(intent); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);

But where i should put this transition code? I dont have any listener for the back button in the action bar.

Thanks in advice guys


Solution

  • The up button in the action bar is treated as a menu item with ID android.R.id.home, as you can read in the docs. There you can find that you can handle clicks on it using this code:

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            // Respond to the action bar's Up/Home button
            return false;
        }
        return super.onOptionsItemSelected(item);
    }