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

标签 android android-toolbar androidx material-components-android material-components

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

这可能吗?

enter image description here

最佳答案

如果您使用的是 Toolbar 更改图标只需使用:

Toolbar toolbar = findViewById(R.id.xxx);
toolbar.setNavigationIcon(R.drawable.xxxx4);
setSupportActionBar(toolbar);
如果您使用 ActionBar 您可以使用:
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.xxx);
您也可以在您的应用主题中将其更改为覆盖 homeAsUpIndicator属性:
  <style name="AppTheme" parent="Theme.MaterialComponents.DayNight">
    <item name="homeAsUpIndicator">@drawable/...</item>
  </style>
如果您使用 导航组件 ,目前没有自定义 HomeAsUpIndicator 图标的方法,当您在非 root 目的地时显示向上按钮是一种预期行为。
有一个解决方法,添加 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);
                }
            }
        });
enter image description here

关于android - 如何在android Material 组件中更改工具栏后退按钮图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62018283/

相关文章:

java - 当重力=顶部时,文本不会从顶部开始

Android:如何/教程将 ActionBar 更改为 ActionBarCompat(工具栏)?

java - 我没有添加对 androidx CoordinatorLayout 和 RecyclerView 库的依赖,但仍然可以使用它

android - 为什么使用AndroidX时嵌套的PreferenceScreen打不开?

尽管在纵向 View 中录制,但使用 mediaRecorder 和表面 View 录制的 Android 视频无法在横向 View 中播放

android - Activity 需要暂停,直到子 Activity 运行(Android)

android - 如何使用android-openCV在android中流式传输多个CameraBridgeViewBase?

android - 使用 SHA256 和 CertificatePinner 在 Volley 中进行 SSL 固定

android - 为什么折叠工具栏标题在工具栏下面?

java - 回收器 View : Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference