onNavigationItemSelected not calling when item is selected

后端 未结 2 1029
南笙
南笙 2021-01-29 14:02

I am adding footer-view in navigation drawer using following code -




        
2条回答
  •  被撕碎了的回忆
    2021-01-29 14:20

    Dear this worked for me the item R.id.nav_logout i needed finish activity and not instance a fragment:

    private lateinit var appBarConfiguration: AppBarConfiguration
    var drawerLayout: DrawerLayout? = null
    var navView: NavigationView? = null
    var navController: NavController? = null
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_customer_main)
        val toolbar: Toolbar = findViewById(R.id.toolbar)
        setSupportActionBar(toolbar)
    
        val fab: FloatingActionButton = findViewById(R.id.fab)
        fab.setOnClickListener { view ->
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show()
        }
    
        drawerLayout = findViewById(R.id.drawer_layout)
        navView = findViewById(R.id.nav_view)
        navController = findNavController(R.id.nav_host_fragment)
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        appBarConfiguration = AppBarConfiguration(setOf(
                R.id.nav_home, R.id.nav_service_requests), drawerLayout)
        setupActionBarWithNavController(navController!!, appBarConfiguration)
        navView!!.setupWithNavController(navController!!)
        navView!!.setNavigationItemSelectedListener(this)
    }
    
    override fun onSupportNavigateUp(): Boolean {
        val navController = findNavController(R.id.nav_host_fragment)
        return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
    }
    
    override fun onNavigationItemSelected(menuItem: MenuItem): Boolean {
        menuItem.isChecked = true
        drawerLayout!!.closeDrawers()
        when (menuItem.itemId) {
            R.id.nav_logout -> {
                Prefs.putBoolean("flagLogin", false)
                val intent = Intent(this@CustomerMainActivity, LoginActivity::class.java)
                startActivity(intent)
                finish()
                return true
            }
        }
        if( navController!!.currentDestination!!.id != menuItem.itemId)
            navController!!.navigate(menuItem.itemId)
        return true
    }
    

提交回复
热议问题