androidandroid-layoutandroid-navigationonbackpressedup-navigation

How to get Up Navigation behavior exactly like back button pressed


How can I get the Up Navigation button to behave like the back button? When I press the back button all my previous activities remain as the were prior. When I press the up button my activities return to initial state. I tried hooking up onBackPressed(); to case R.id.home on my onOptionsItemSelected but it still behaves differently.

Visual: Back Button Behavior- https://www.flickr.com/photos/151974643@N07/35702817566/in/dateposted-public/ Up Button Behavior - https://www.flickr.com/photos/151974643@N07/35702812926/in/dateposted-public/ Any help would be appreciated. Thank you!


Solution

  • You can do it several ways, put this code in onCreate() method of your activity

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            YOUR_ACTIVITY.this.onBackPressed();
        }
    });
    

    Hope it helps.