简体   繁体   English

如何更改 android 材料组件中的工具栏后退按钮图标

[英]How to change toolbar back button icon in android material components

I would like to change the default navigate up icon (back button icon) to my custom icon.我想将默认的向上导航图标(后退按钮图标)更改为我的自定义图标。 I not using a drawer, just a simple toolbar and material components我没有使用抽屉,只是一个简单的工具栏和材质组件

Is this possible?这可能吗?

在此处输入图像描述

If you are using a Toolbar to change the icon just use:如果您使用Toolbar更改图标,只需使用:

Toolbar toolbar = findViewById(R.id.xxx);
toolbar.setNavigationIcon(R.drawable.xxxx4);
setSupportActionBar(toolbar);

If you are using the ActionBar you can use:如果您使用的是ActionBar ,您可以使用:

getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.xxx);

You can also change it overriding in your app theme the homeAsUpIndicator attribute:您还可以在您的应用主题中将其更改为覆盖homeAsUpIndicator属性:

  <style name="AppTheme" parent="Theme.MaterialComponents.DayNight">
    <item name="homeAsUpIndicator">@drawable/...</item>
  </style>

If you are using the Navigation Components , currently there isn't a way to customize the HomeAsUpIndicator icon, and it is an expected behavior with the Up button displayed when you are on a non-root destination.如果您使用的是Navigation Components ,则目前无法自定义 HomeAsUpIndicator 图标,这是一种预期行为,当您位于非根目的地时会显示 Up 按钮。
There is a workaround adding an addOnDestinationChangedListener after your setup method and checking the destination.有一种解决方法,在您的设置方法后添加addOnDestinationChangedListener并检查目标。
Something like:就像是:

navController.addOnDestinationChangedListener(
        new NavController.OnDestinationChangedListener() {
            @Override
            public void onDestinationChanged(@NonNull NavController controller, @NonNull NavDestination destination, @Nullable Bundle arguments) {
                if (destination.getId() == R.id.nav_xxx) {
                    //With ActionBar                        
                    //getSupportActionBar().setHomeAsUpIndicator(R.drawable.xxxx);

                    //With a Toolbar
                    toolbar.setNavigationIcon(R.drawable.xxxx);
                }
            }
        });

在此处输入图像描述

If you have created a toolbar and set it as an ActionBar like below如果您创建了一个工具栏并将其设置为如下所示的ActionBar

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

You have two options in setting a custom icon:设置自定义图标有两种选择:

Option 1选项1

toolbar?.setNavigationIcon(R.drawable.homeNavigationIcon)

Option 2选项 2

supportActionBar?.setHomeAsUpIndicator(R.drawable.homeNavigationIcon)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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