【问题标题】:BottomNavigationView, how to call a function on one item, and use AppBarConfiguration for the others?BottomNavigationView,如何在一个项目上调用函数,并为其他项目使用 AppBarConfiguration?
【发布时间】:2021-01-30 10:42:11
【问题描述】:

这是配置BottomNavigationView导航的常规方式:

    val appBarConfiguration = AppBarConfiguration(setOf(R.id.navigation_home, R.id.navigation_months, R.id.navigation_due_date_calculator))
    setupActionBarWithNavController(navController, appBarConfiguration)
    navView.setupWithNavController(navController)

但是,如果你想为一个按钮调用一个函数而不是打开一个片段,会发生什么?

我试过这个:

navView.setOnNavigationItemSelectedListener {
            when (it.itemId){
                R.id.navigation_other_useful_apps -> {
                    Toast.makeText(applicationContext, "Other Useful Apps", Toast.LENGTH_SHORT).show()
                    true
                }
                else -> true
            }
        }

问题是当我添加该方法时,导航不再起作用。如何在一项上调用函数,而在其他项上使用AppBarConfiguration

【问题讨论】:

    标签: android kotlin bottomnavigationview android-bottomnavigationview


    【解决方案1】:

    你必须重写onOptionsItemSelected函数,它会调用函数而不是打开片段

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
            when (item.itemId) {
                R.id.navigation_other_useful_apps -> {
                    Toast.makeText(applicationContext, "Other Useful Apps", Toast.LENGTH_SHORT).show()
                    return true;
                }
    
            }
            return super.onOptionsItemSelected(item)
        }
    

    或者试试这个

    navView.menu.findItem(R.id.navigation_other_useful_apps )
            .setOnMenuItemClickListener { menuItem: MenuItem? ->
                    Toast.makeText(applicationContext, "Other Useful Apps", Toast.LENGTH_SHORT).show()
                true
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-03
      • 2015-04-22
      • 2022-01-06
      • 1970-01-01
      • 2021-06-14
      • 1970-01-01
      相关资源
      最近更新 更多