Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable action bar back button like hardware back button

Tags:

android

I have many fragments in an activity. I move to some activity from one of the fragments. There are two cases. If I press hardware back button, I move back to the fragment from which current activity was called. But using action bar back button, previous activity is launched from onCreate state,like the very first fragment that I use when that activity is launched at first. Here is the code for action bar back button for second activity: in onCreate: getActionBar().setDisplayHomeAsUpEnabled(true); then I use:

 @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
            case android.R.id.home:
                NavUtils.navigateUpFromSameTask(this);
                return true;
            default:
                return super.onOptionsItemSelected(item);
            }
        }

How do I get the same function in action bar back button as in hardware bach button: onbackpressed??

like image 550
Ali Hassan Avatar asked Jun 06 '14 12:06

Ali Hassan


People also ask

How do I customize my action bar?

This example demonstrate about how to create a custom action bar in Android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.


2 Answers

You can call the method onBackPressed(); of the Activity to give you the ability to back button just like the hardware back button.

if you are in fragment call getActivity().onBackPressed()

like image 146
Rod_Algonquin Avatar answered Oct 02 '22 08:10

Rod_Algonquin


In the switch statement, change

case android.R.id.home:
    NavUtils.navigateUpFromSameTask(this);
    return true;

to

case android.R.id.home:
    onBackPressed();
    return true;
like image 33
Ryan Clarke Avatar answered Oct 02 '22 08:10

Ryan Clarke