其他分享
首页 > 其他分享> > Android BottomNavigation未正确使用导航控制器突出显示

Android BottomNavigation未正确使用导航控制器突出显示

作者:互联网

我正在尝试从Android架构组件实现Nagivation.我能够在我的片段中成功导航.我试图将它附加到我的底部导航但我无法正确使用它.我可以使用Navigation.findNavController(View).navigate(R.id.Fragment)成功地在片段之间导航,但是当我使用任何UI组件或后退按钮执行此操作时,我底部导航中的突出显示不会更改,如下所示GIF

enter image description here

MainActivity.kt的代码如下,

class MainActivity : AppCompatActivity() {


    private lateinit var navController: NavController


    private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
        when (item.itemId) {
            R.id.navigation_home -> {
                navController.navigate(R.id.homeFragment)
                return@OnNavigationItemSelectedListener true
            }
            R.id.navigation_dashboard -> {
                navController.navigate(R.id.addEmotionFragment)
                return@OnNavigationItemSelectedListener true
            }
            R.id.navigation_notifications -> {
                return@OnNavigationItemSelectedListener true
            }
        }
        false
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        navController = Navigation.findNavController(this, R.id.nav_host)
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)
    }


}

对于HomeFragment.kt

class HomeFragment : Fragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_home, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        button.setOnClickListener {
            Navigation.findNavController(it).navigate(R.id.addEmotionFragment)
        }
    }
}

解决方法:

尝试使用navigation-ui.

implementation 'androidx.navigation:navigation-ui:' + navigationVersion //currently 1.0.0-alpha05

在活动中

    navController = Navigation.findNavController(this, R.id.nav_host)
    NavigationUI.setupWithNavController(bottomNavigation, navController)

并确保您的片段ID匹配菜单ID.

<item
        android:id="@+id/homeFragment"
        android:title="Home"/>

标签:bottomnavigationview,android,android-architecture-components,android-jetpack,and
来源: https://codeday.me/bug/20190828/1746513.html