"Back button" using getSupportActionbar and appcompat v7 toolbar
Asked Answered
S

8

50

I'm using the new toolbar from the Appcompat V7 library and I'm making an application with navigation drawer and with fragments.

In some fragments I don't want to show the hamburger icon but the arrow instead... That is fine I did this in this way:

mDrawerToggle.setDrawerIndicatorEnabled(false);

mDrawerToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);

getSupportActionBar().setHomeAsUpIndicator(R.drawable.abc_ic_ab_back_mtrl_am_alpha);

My question is that: How or where i need to set up the home button lisener or what i need to listen for the "back" button ? I want to call the main backpressed method and to set back the navigation drawer icon with the hamburger icon..

Stringhalt answered 1/12, 2014 at 14:42 Comment(0)
W
42

You can do it like this:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);  
    toolbar = (Toolbar)findViewById(R.id.toolbar);
    if (toolbar != null) {
      setSupportActionBar(toolbar);
      getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    setUpNavigationDrawer();

    getFragmentManager().addOnBackStackChangedListener(backStackListener); // listen to the backstack of the fragment manager
}

Define the onBackSTackChangedListener:

private FragmentManager.OnBackStackChangedListener backStackListener = new FragmentManager.OnBackStackChangedListener() {
   @Override
   public void onBackStackChanged() {
       setNavIcon();
   };
}

Set the icon according to your fragment's backstack:

protected void setNavIcon() {
    int backStackEntryCount = getFragmentManager().getBackStackEntryCount();
    drawerToggle.setDrawerIndicatorEnabled(backStackEntryCount == 0);
}

Detect when the drawer icon is pressed:

public boolean onOptionsItemSelected(MenuItem item) {
    if (drawerToggle.isDrawerIndicatorEnabled() && drawerToggle.onOptionsItemSelected(item)) {
        return true;
    }

    switch (item.getItemId()) {
      case x:
         return true;
      default:
         return false;
    }
}

And handle the up button:

public boolean onSupportNavigateUp() {
    onBackPressed();
    return true;
}

This works for me. Good luck.

Washko answered 17/4, 2015 at 7:35 Comment(2)
What's case x supposed to be?Thar
@Washko : how to receive back arrow click?Queridas
C
71

Add this method in onCreate():

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

Then override the onOptionItemSelected() as below:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            onBackPressed();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}
Chartography answered 9/10, 2015 at 14:42 Comment(0)
W
42

You can do it like this:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);  
    toolbar = (Toolbar)findViewById(R.id.toolbar);
    if (toolbar != null) {
      setSupportActionBar(toolbar);
      getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    setUpNavigationDrawer();

    getFragmentManager().addOnBackStackChangedListener(backStackListener); // listen to the backstack of the fragment manager
}

Define the onBackSTackChangedListener:

private FragmentManager.OnBackStackChangedListener backStackListener = new FragmentManager.OnBackStackChangedListener() {
   @Override
   public void onBackStackChanged() {
       setNavIcon();
   };
}

Set the icon according to your fragment's backstack:

protected void setNavIcon() {
    int backStackEntryCount = getFragmentManager().getBackStackEntryCount();
    drawerToggle.setDrawerIndicatorEnabled(backStackEntryCount == 0);
}

Detect when the drawer icon is pressed:

public boolean onOptionsItemSelected(MenuItem item) {
    if (drawerToggle.isDrawerIndicatorEnabled() && drawerToggle.onOptionsItemSelected(item)) {
        return true;
    }

    switch (item.getItemId()) {
      case x:
         return true;
      default:
         return false;
    }
}

And handle the up button:

public boolean onSupportNavigateUp() {
    onBackPressed();
    return true;
}

This works for me. Good luck.

Washko answered 17/4, 2015 at 7:35 Comment(2)
What's case x supposed to be?Thar
@Washko : how to receive back arrow click?Queridas
J
31

Not sure if this works in OP's case, but in many cases this is probably the simplest option to implement Back button with the AppCompat Toolbar.

Skip all the setHomeButtonEnabled, setDisplayHomeAsUpEnabled and onOptionsItemSelected stuff, and related issues.

Instead, when initialising the Toolbar, simply set 1) navigation icon and 2) navigation OnClickListener for it:

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

if (enableBackNavigation) {
    toolbar.setNavigationIcon(R.drawable.ic_back);
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onBackPressed();
        }
    });
}
Jaredjarek answered 23/4, 2015 at 13:37 Comment(1)
This doesn't stop swipe from edge to pull the navigation drawerCopula
M
16

1- Create Toolbar layout;

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:local="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/dark_blue"
    android:minHeight="?attr/actionBarSize"
    local:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    local:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />

2- Include this in your layout at the place where you want the toolbar to be.

3- Paste the following code in your activity.(extends ActionBarActivity)

private Toolbar mToolbar;

//For Toolbar (Action bar) start
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        mToolbar.setNavigationIcon(R.drawable.ic_back_arrow);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        getSupportActionBar().setTitle("Event Details");
        //For Toolbar (Action bar) end

4- change the back click icon to whatever you want.

Mohur answered 26/8, 2015 at 6:50 Comment(1)
This is a very clear, easy to understand, efficient and reusable solution. I would have done it the same way! Well done! ;)Sweetheart
L
3

activate the back button:

getActionBar().setDisplayHomeAsUpEnabled(enable);

and listen for clicks in onBackPressed()

Obviously your activity must extend ActionBarActivity

Libretto answered 1/12, 2014 at 15:2 Comment(0)
R
2

Simply you can set Navigation icon and make sure you are setting setNavigationOnClickListener() after setting setSupportActionBar(toolbar)

toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_arrow_back));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        onBackPressed();
    }
});
Rules answered 4/1, 2016 at 8:11 Comment(0)
S
1

in manifest add these lines under the activity you want the back arrow working

android:parentActivityName="Your parent activity name"

Samualsamuel answered 1/11, 2017 at 14:57 Comment(0)
C
0

Add setDisplayHomeAsUpEnabled(true)

    Toolbar toolbar  = findViewById(R.id.toolbar);
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

Handle the back button

   public boolean onSupportNavigateUp() {
    onBackPressed();
    return true;
}
Castellated answered 18/1, 2019 at 3:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.