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

Jam*_*med 4 android android-toolbar material-components material-components-android androidx

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

这可能吗?

在此处输入图片说明

Gab*_*tti 5

如果您使用 aToolbar更改图标,请使用:

Toolbar toolbar = findViewById(R.id.xxx);
toolbar.setNavigationIcon(R.drawable.xxxx4);
setSupportActionBar(toolbar);
Run Code Online (Sandbox Code Playgroud)

如果您正在使用,则ActionBar可以使用:

getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.xxx);
Run Code Online (Sandbox Code Playgroud)

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

  <style name="AppTheme" parent="Theme.MaterialComponents.DayNight">
    <item name="homeAsUpIndicator">@drawable/...</item>
  </style>
Run Code Online (Sandbox Code Playgroud)

如果您使用的是Navigation Components,目前还没有自定义 HomeAsUpIndicator 图标的方法,这是当您位于非根目标位置时显示向上按钮的预期行为。
有一种解决方法是addOnDestinationChangedListener在您的设置方法之后添加一个并检查目的地。
就像是:

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);
                }
            }
        });
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

  • 请小心,首先调用 setupWithNavController(),然后再调用 addOnDestinationChangedListener()。 (3认同)
  • 谢谢你,“导航组件”解决方法救了我的命 (3认同)