Search code examples
javaandroidandroid-toolbarback-button

Difference between toolbar back button and onBackPressed method


I have an app which has multiple activities. One example would be my MainActivity which displays a list of items from where you can open a "detail" overview of certain item.

Once click an item to open it I open another activity like this

final Intent intent = new Intent(getApplicationContext(), AddActivity.class);
getApplicationContext().startActivity(intent);

Once the activity is opened in its toolbar I have a back button. I guess that button comes out of the box since I am using android.support.v7.widget.Toolbar.

In case where on MainActivity I have scrolled far in the list and then decide to open a new activity and on that new activity I click toolbar back button I am returned to MainActivity but its refreshed (its OnCreate method gets called).

In case where I open second activity and it has a button that performs some action and at the end returns you to MainActivity calling onBackPressed() from FragmentActivity that is extended (by extending AppCompatActivity), it would return you to MainActivity but without any refreshing you would be able to continue where you stopped.

My question is if it is possible to replace current behavior of toolbar back button with this onBackPressed() behavior?


Solution

  • I have made it work. All I needed to do was to override onSupportNavigateUp in order to get same behavior on both buttons.

    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed(); // one inherited from android.support.v4.app.FragmentActivity
    
        return false;
    }