如何在Android材质组件中更改工具栏的后退按钮图标 [英] How to change toolbar back button icon in android material components

查看:77
本文介绍了如何在Android材质组件中更改工具栏的后退按钮图标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将默认的向上导航图标(后退按钮图标)更改为我的自定义图标.我没有使用抽屉,只是一个简单的工具栏和材料组件

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

这可能吗?

推荐答案

如果您使用的是 工具栏 更改图标,只需使用:

If you are using a Toolbar to change the icon just use:

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

如果您使用的是 ActionBar ,则可以使用:

If you are using the ActionBar you can use:

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

您还可以在应用程序主题中的 homeAsUpIndicator 属性中更改它的覆盖范围:

You can also change it overriding in your app theme the homeAsUpIndicator attribute:

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

如果您使用的是导航组件,则目前尚无法自定义HomeAsUpIndicator图标,这是一种预期的行为,当您位于非root用户上时会显示向上"按钮目的地.
有一种解决方法,在您的设置方法之后添加 addOnDestinationChangedListener 并检查目标位置.
像这样:

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.
There is a workaround adding an addOnDestinationChangedListener after your setup method and checking the destination.
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);
                }
            }
        });

这篇关于如何在Android材质组件中更改工具栏的后退按钮图标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆