【问题标题】:Using BottomNavigationView to change FloatingActionButton Icon使用 BottomNavigationView 更改 FloatingActionButton 图标
【发布时间】:2021-10-10 07:36:29
【问题描述】:

BottomNavigationView.setOnItemSelectedListener 覆盖了基本行为,但我想扩展而不是覆盖,我该怎么做?

我有一个 4 片段应用程序,我使用 MainActivity 上的材料 BottomNavigationView (navView)。我在 MainActivity 上有一个 FloatingActionButton (fab)。当我单击 navView 项目时,除了导航到所选片段之外,我还想更改 fab 上的图标。我想使用 navView 的默认导航行为,但是使用 navView.setOnItemSelectedListener (使用它来更改图标),我失去了预期的基本行为,更改片段。返回 true 或 false 没有帮助。

我想这样做,也想改变片段。如何使用 navView 的继承行为进行导航

 binding.navView.setOnItemSelectedListener {item ->
        val str =item.itemId.toString()
        Snackbar.make(binding.root, str, Snackbar.LENGTH_SHORT)
            .setAction("Action", null)
            .show()
        return@setOnItemSelectedListener true // false, behavior appears the same

【问题讨论】:

    标签: android kotlin android-fragments


    【解决方案1】:

    我没有使用默认行为,我编写了代码来导航。

    1. 这会调用方法来导航到片段并设置 fab 的初始图标

      私人乐趣 setupNavController() { val navHostFragment = supportFragmentManager .findFragmentById(...) as NavHostFragment val navController = navHostFragment.navController NavigationUI.setupWithNavController( binding.navView, 导航控制器 ) binding.navView.setOnItemSelectedListener {item -> when (item.itemId) { // 需要方法调用,因为不能做 fab in -> R.id.navigation_1 -> F1() R.id.navigation_2 -> F2() R.id.navigation_3 -> F3() R.id.navigation_4 -> F4() } return@setOnItemSelectedListener true } }

    2. 这会响应 fab 点击

      私人乐趣 setFabNavigationAndIcon() { val currentBottomMenuId = binding.navView.selectedItemId 当(currentBottomMenuId){ R.id.navigation_dashboard -> {
      val intent = Intent(this, AnActivity::class.java).apply { } 开始活动(意图) } R.id.f1 -> { ... } R.id.f2 -> { binding.fragmentContainerView.findNavController().navigate(... // 改变图标
      binding.fab.setImageDrawable( 资源.getDrawable( ... baseContext.theme ) ) } R.id.f3 -> { binding.fragmentContainerView.findNavController().navigate(... // 更改图标以便用户可以返回列表

           }
       }
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-08
      • 1970-01-01
      • 2022-10-14
      • 2020-04-14
      • 2021-04-21
      相关资源
      最近更新 更多