使用NavHostFragment
时,我试图(没有成功)更改工具栏上的后退箭头图标。我正在将NavController
用于工具栏(如您在此处看到的那样)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
val navController = findNavController(R.id.nav_host_fragment)
appBarConfiguration = AppBarConfiguration(navController.graph)
setupActionBarWithNavController(navController, appBarConfiguration)
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)
toolbar.setTitleTextColor(resources.getColor(R.color.toolbarTextColor))
navigation.setupWithNavController(Navigation.findNavController(this, R.id.nav_host_fragment))
}
导航正常,但我似乎无法更改后退图标。
我已经尝试使用自定义主题。到目前为止,定义的属性都没有起作用。
<style name="ToolbarTheme" parent="@style/ThemeOverlay.AppCompat.ActionBar">
<item name="android:navigationIcon">@drawable/ic_keyboard_arrow_left_black_24dp</item>
<item name="android:homeAsUpIndicator">@drawable/ic_keyboard_arrow_left_black_24dp</item>
<item name="collapseIcon">@drawable/ic_keyboard_arrow_left_black_24dp</item>
<item name="android:closeIcon">@drawable/ic_keyboard_arrow_left_black_24dp</item>
</style>
尝试使用代码:
toolbar.navigationIcon = resources.getDrawable(R.drawable.ic_keyboard_arrow_left_black_24dp)
toolbar.setNavigationIcon(R.drawable.ic_keyboard_arrow_left_black_24dp)
toolbar.navigationIconResource = R.drawable.ic_keyboard_arrow_left_black_24dp
使用代码时,一旦创建了布局,就会出现后退按钮,但是当我输入另一个片段时,该图标会变回默认的后退图标。
我该如何更改?
答案 0 :(得分:1)
此功能应在将来添加,目前可以通过实现“ OnDestinationChangedListener”并更改回调中的工具栏图标(只需确保在设置方法之后添加“ OnDestinationChangedListener”)来实现。 :
navController.addOnDestinationChangedListener { controller, destination, arguments ->
toolbar.setNavigationIcon(R.drawable.ic_keyboard_arrow_left_black_24dp) //set it here for all the destinations, or inside the switch statement if you want to change it based on destination
when(destination.id) {
R.id.mainFragment -> {
toolbar.setNavigationIcon(R.drawable.ic_keyboard_arrow_left_black_24dp)
}
R.id.detailsFragment -> {
toolbar.setNavigationIcon(R.drawable.ic_keyboard_arrow_left_black_24dp)
}
}
}
基于此问题: