简体   繁体   中英

Disable Toolbar's Up Button

How can you disable the default "UP" button in Toolbar beside the ic_launcher? I want to leave only the ic_launcher at the left.

在此处输入图片说明

If you're using Toolbar ( android.support.v7.widget.Toolbar or native) in order to disable navigation button just call:

toolbar.setNavigationIcon(null);

From documentation:

 /**
 * Set the icon to use for the toolbar's navigation button.
 * ...
 *  @param icon Drawable to set, may be null to clear the icon
 */
 public void setNavigationIcon(@Nullable Drawable icon) { ... }

What Alex K has suggested is for the Back button in navigation bar at the bottom of the screen - not Up icon at the top left corner of the screen.

For the ActionBar up icon you need to add this:

    getActionBar().setDisplayHomeAsUpEnabled(false);

Also, in your manifest.xml file, you could delete the parent metadata if there is any:

        <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="com.example.ParentActivity" />

Insert this code to the Activity where you want to hide UP button from Toolbar:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // remove UP button
    if (getSupportActionBar() != null) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
    }
}

I meet the similar question, the empty navigationIcon holder the left space.

use app:contentInsetLeft="0dp" in the xml of <android.support.v7.widget.Toolbar> , it fixs

There are two ways in the manifest which cause the Up navigation to appear in the AppBar. As mentioned by @Kasira:

<meta-data android:name="android.support.PARENT_ACTIVITY" android:value="com.example.ParentActivity" />

And also if the <activity> tag contains: android:parentActivityName=".activity.ParentActivtyName"

I did a lot of searching online but I could not find any solution to this problem. So, I poked around in the source code a little bit and came to this solution:

val field = Class.forName("androidx.appcompat.widget.Toolbar").getDeclaredField("mNavButtonView")
field.isAccessible = true
val toolbarUpButton = field.get(findViewById(R.id.main_toolbar)) as? ImageButton
toolbarUpButton?.isEnabled = false

This does not hide the up button but disables it and if you want to indicate that the button is disabled you can use the following selector as the color for your drawable:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/enabled" android:state_enabled="true"/>
    <item android:color="@color/disabled" android:state_enabled="false"/>
    <item android:color="@color/enabled" />
</selector>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM