mpanga
mpanga

Reputation: 107

How do I make the back button in the toolbar behave like the physical button on the device?

I have an android application with a main activity, which is passed information from the login Activity. Whenever I access another activity from the MainActivity, and I use the back button on the bottom of the android device, the MainActicity is restarted at its previous state. However if I use the back button in the toolbar or Actionbar, the MainActivity is reset and this clears out the information that was previously passed from the loginActivity? How can I have the back button at the top behave more like the one on the bottom?

Would I have to find a way of passing the information from the database without actually assessing the login screen? How would I go about this. This information can only be passed if the user enters the correct login iformation.

Upvotes: 3

Views: 725

Answers (2)

Cardo
Cardo

Reputation: 621

To reproduce the hard/soft key for navigating back on Android you can just finish() the activity, like this:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()) {
        case android.R.id.home:
            finish();
            return true; //this does the trick
    }
    return super.onOptionsItemSelected(item);
}

Upvotes: 0

Yusuf Eren Utku
Yusuf Eren Utku

Reputation: 1809

The toolbar back button will work as hierarchically. But device back button works as pop-up stash. So thats why when you use device back button your information not disappearing. But when you are using toolbar/action bar back/home button. It will call the one up activity and re-create that activity for user use. In that point you are losing your data. You can save your data in bundle or just do what device back button doing. With that knowledge here you can do; You can call the super.onBackPressed();

Here an example:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
        switch ( item.getItemId() ) {
              case android.R.id.home:
                super.onBackPressed();
        }
        return super.onOptionsItemSelected(item);
}

Edit: You can save your activity state. Here is a good example for this: Saving Android Activity state using Save Instance State

Upvotes: 1

Related Questions