How provide Up navigation with toolbar's home button on v7 toolbar
Asked Answered
C

8

20

I have a toolbar in my activity ( import android.support.v7.widget.Toolbar; ) and I'm trying to provide Up navigation using its home button. What I have:

Manifest:

<!-- ... -->
<activity android:name=".SettingsActivity"
          android:label="@string/settings"
          android:parentActivityName=".MainActivity"/>
<!-- ... -->

view_toolbar.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fitsSystemWindows="true"
    android:minHeight="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:elevation="4dp">
</android.support.v7.widget.Toolbar>

activity_settings.xml :

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- Toolbar -->
    <include
        layout="@layout/view_toolbar" />

    <!-- ... -->

my onCreate method:

super.onCreate(bundle)
setContentView(R.layout.activity_settings);

// Set the toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

setSupportActionBar(toolbar);

So far I shouldn't have an up button and I don't. So we're fine. But when I tried to add it, I couldn't.

First I tried this:

getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

Didn't work. Then I tried this (as shown here):

toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
    Toast.makeText(ToolbarActivity.this, "Up clicked", 
        Toast.LENGTH_SHORT).show();
    NavUtils.navigateUpFromSameTask(ToolbarActivity.this);
}
});

I even tried a workaround I saw somewhere, involving creating a dummy menu and trying to get the event from onOptionsItemSelected (which is never called by the way).

What can I do? What is the correct way to provide Up navigation through toolbar?

Chipper answered 15/12, 2015 at 0:9 Comment(5)
Because you declare parent activity on manifest, so I think this answer may help: https://mcmap.net/q/134869/-how-can-i-return-to-a-parent-activity-correctlyFrobisher
What class extends your Activity?Cherub
@Cherub AppCompatActivityChipper
Did you find a solution to your issue? I am facing the same thing. For me the Back button or home icon does not give a call to onOptionMenuSelected neither in Fragment nor in the Activity.Overcurious
@Overcurious What about onOptionsItemSelected ?? Anyway.. The main idea is to catch the event from android.R.id.home button and finish() your activity there. Try "Daniel Martin Shum"'s answer below. What he says is right, even though it didn't solve my problem at the time.Chipper
E
4

It's very simple. Just do the following steps:

  1. Add the toolbar to the activity_child.xml:

(In my project, this AppBarLayout is placed inside a ConstraintLayout)

<android.support.design.widget.AppBarLayout
            android:id="@+id/appBarLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/AppTheme.AppBarOverlay"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

...
  1. Set up the toolbar in the ChildActivity.java
public class ChildActivity extends AppCompatActivity
{

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_child);

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_arrow_back_black_24dp);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
  }

  ...
}

  1. set the parentActivityName property in AndroidManifest.xml
<activity android:name=".ChildActivity"
            android:theme="@style/AppTheme.NoActionBar"
            android:parentActivityName=".ParentActivity"/>

Important

For this to work properly, do not call finish() in the parent activity after you call startActivity(intent).

Ecdysis answered 19/1, 2019 at 19:3 Comment(1)
Since I asked that question I've solved the problem many times with many different ways. I'll accept your answer because it's more updated than @Daniel Martin Shum answer. Sorry I took too long. I haven't logged in for ages.Chipper
D
16

Did you have the below code to set your toolbar as the default activity actionbar?

setSupportActionBar(toolbar);

You did not set an image icon to the home button, maybe it shows up, but you just can't see it.

getSupportActionBar().setHomeAsUpIndicator(iconDrawable);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

and as @Gonzalo said, you also have to override the menu select event to handle the home button onClick event

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    // Respond to the action bar's Up/Home button
    case android.R.id.home:
        //handle the home button onClick event here.
        return true;
    case android.R.id.other_menu
        return true
    }

    return super.onOptionsItemSelected(item);
}

and why didn't you have a appbarlayout to contain the toolbar?

<android.support.design.widget.AppBarLayout
        android:id="@+id/baseAppbarLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.Toolbar
            android:id="@+id/baseToolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

</android.support.design.widget.AppBarLayout>

More actionbar implement details please have a look at my github project, hope it can help:

java code https://github.com/DanielShum/MaterialAppBase/blob/master/materialAppBaseLibrary/src/main/java/com/daililol/material/appbase/base/BaseActionbarActivity.java

xml code https://github.com/DanielShum/MaterialAppBase/blob/master/materialAppBaseLibrary/src/main/res/layout/base_actionbar_activity.xml

Danner answered 15/12, 2015 at 2:46 Comment(1)
Thank you for your help. I tried using the appbarlayout but it didn't work. Also, the back icon appears. I can see it normally but my pressing has no effect.Chipper
C
12

1- set your toolbar

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

2- setup your icon

    if (toolbar != null) {
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);

    }

3- override this method

@Override
public boolean onSupportNavigateUp() {
    onBackPressed();
    return true;
}
Cardboard answered 18/11, 2017 at 9:9 Comment(1)
NB I didn't need to #setHomeButtonEnabled(true) when targetSDK=30 even though the doco says otherwise.Jotham
E
4

It's very simple. Just do the following steps:

  1. Add the toolbar to the activity_child.xml:

(In my project, this AppBarLayout is placed inside a ConstraintLayout)

<android.support.design.widget.AppBarLayout
            android:id="@+id/appBarLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/AppTheme.AppBarOverlay"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

...
  1. Set up the toolbar in the ChildActivity.java
public class ChildActivity extends AppCompatActivity
{

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_child);

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_arrow_back_black_24dp);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
  }

  ...
}

  1. set the parentActivityName property in AndroidManifest.xml
<activity android:name=".ChildActivity"
            android:theme="@style/AppTheme.NoActionBar"
            android:parentActivityName=".ParentActivity"/>

Important

For this to work properly, do not call finish() in the parent activity after you call startActivity(intent).

Ecdysis answered 19/1, 2019 at 19:3 Comment(1)
Since I asked that question I've solved the problem many times with many different ways. I'll accept your answer because it's more updated than @Daniel Martin Shum answer. Sorry I took too long. I haven't logged in for ages.Chipper
C
2

You can do it like this.

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(R.string.title);
toolbar.setNavigationIcon(R.mipmap.back); // just setNavigationIcon
setSupportActionBar(toolbar);

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        // Respond to the toorbar's NavigationIcon as up/home button
        case android.R.id.home:
            //NavigationIcon
            return true;
    }
    return super.onOptionsItemSelected(item);
}
Cutcherry answered 15/12, 2015 at 2:56 Comment(2)
If you want to use toolbar, you should set your Activity noactionbar style. Such as: <style name="AppTheme.NoActionBar"> <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item> </style>Cutcherry
The toolbar itself IS working. The problem is with the home button. The toolbar is up and running.Chipper
A
1

I found a simple way. Which works perfectly according to expectation.

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_id);
    toolbar.setTitleTextColor(Color.WHITE);
    toolbar.setTitle(getResources().getString(R.string.your_title));
    toolbar.setNavigationIcon(R.mipmap.back_btn);
    setSupportActionBar(toolbar);

    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onBackPressed();  // byDefault provided backPressed method, or handle your own way
        }
    });
Archiearchiepiscopacy answered 27/7, 2017 at 7:27 Comment(0)
A
1

One can select by ID home, when binding the event with ViewDataBinding:

this.getDataBinding().toolbarProducts.home.setOnClickListener(view -> {
    NavController controller = Navigation.findNavController(getDataBinding().getRoot());
    controller.navigateUp();
});

Nothing else worked for me inside a Fragment.

Antiserum answered 9/10, 2021 at 14:32 Comment(0)
C
0

As far as I know the back button of the toolbar is treated as a menu item, so as you say you should override the onOptionsItemSelected.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    // Respond to the action bar's Up/Home button
    case android.R.id.home:
        //Home/back button
        return true;
    }
    return super.onOptionsItemSelected(item);
}
Cherub answered 15/12, 2015 at 0:19 Comment(1)
Tried it. Not working. The onOptionsItemSelected is never call, as I state in my post.Chipper
F
0

I too had this kind of issue earlier. I suspect there is something going on with include. Try to add an id to the toolbar included layout like

<include
    layout="@layout/view_toolbar"
    id = "@+id/incl_toobar"/>

And now try to get the toolbar using incl_toolbar.

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

Hope this helps.

Regards,
Sree

Firstclass answered 15/12, 2015 at 0:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.