Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make my ActionBar's "Up" button work like the phone's "Back" button?

I have a ViewPager with Fragments. When a button is clicked in the Fragment, I launch an Activity on mine. Pressing the back button on my phone when I'm in the Activity, takes me back to my previous screen i.e. the one with the Fragments in the ViewPager.

I'd like to enable the "up" button in my ActionBar and in order to do so, I've written the following code:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.detail);

    ActionBar actionBar = getActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
}

Now the "up" button is shown, but clicking it doesn't take me back to the previous screen. I'd like the "up" button to the same thing as the "back" button.

How can I do this? What am I doing wrong?

Thanks.

like image 586
Mridang Agarwalla Avatar asked Oct 02 '12 08:10

Mridang Agarwalla


People also ask

How do I get the back arrow on my Android?

Show back button using actionBar. setDisplayHomeAsUpEnabled(true) this will enable the back button. Custom the back event at onOptionsItemSelected. This will enable the back function to the button on the press.

How can enable back button in Android Action Bar?

This example demonstrates How to get action bar tittle 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.


1 Answers

You need also to implement what should be done when the up button is clicked:

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

    return super.onOptionsItemSelected(item);
}
like image 173
Nermeen Avatar answered Sep 28 '22 06:09

Nermeen