As per the AppBarConfiguration documentation:
NavigationUI
uses an AppBarConfiguratio
n object to manage the behavior of the Navigation button in the upper-left corner of your app's display area. The Navigation button’s behavior changes depending on whether the user is at a top-level destination.
A top-level destination is the root, or highest level destination, in a set of hierarchically-related destinations. Top-level destinations do not display an Up button in the top app bar because there is no higher level destination. By default, the start destination of your app is the only top-level destination.
When the user is at a top-level destination, the Navigation button becomes a drawer icon if the destination uses a DrawerLayout. If the destination doesn't use a DrawerLayout, the Navigation button is hidden. When the user is on any other destination, the Navigation button appears as an Up button.
Therefore if you want to have the Drawer icon appear on multiple destinations and not just the start destination, you need to create an AppBarConfiguration
object with exactly what destinations you want to be top-level destinations:
// Use the IDs from your navigation graph
val appBarConfiguration = AppBarConfiguration(
setOf(R.id.rulesFragment, R.id.aboutFragment),
drawerLayout)
Thus, your code becomes:
class MainActivity : AppCompatActivity() {
private lateinit var appBarConfiguration : AppBarConfiguration
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
@Suppress("UNUSED_VARIABLE")
val binding = DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main)
// Use the Kotlin extension in navigation-ui-ktx to create
// the AppBarConfiguration
appBarConfiguration = AppBarConfiguration(
setOf(R.id.rulesFragment, R.id.aboutFragment),
binding.drawerlayout)
val navController = findNavController(R.id.myNavHostFragment)
// To support up action and also the title, the third parameter is optional and is used
// for the hamburger menu for drawer.
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration)
// show the navigation drawer
NavigationUI.setupWithNavController(binding.navView, navController)
}
override fun onSupportNavigateUp(): Boolean {
val navController = findNavController(R.id.myNavHostFragment)
// this is for the hamburger menu
return NavigationUI.navigateUp(navController, appBarConfiguration)
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…