单击项目时底部导航不导航

问题描述 投票:0回答:1

我有一个底部导航菜单,其中包含3个项目:主页,收藏夹和设置。我正在使用片段容器:<FrameLayout android:id="@+id/fragment_container" /><com.google.android.material.bottomnavigation.BottomNavigationView app:menu="@menu/bottom_navigation_menu" />在BaseFragment中,我想实际导航到的地方是使用setOnNavigationItemSelectedListener,其中我重写了onNavigationItemSelected(item:MenuItem)函数

        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        childFragmentManager.beginTransaction().replace(R.id.fragment_container, BeerListFragment())
            .commit()
        val bottomNavigationView: BottomNavigationView? = view?.findViewById(R.id.bottom_navigation)
        bottomNavigationView?.setOnNavigationItemSelectedListener(object :
            BottomNavigationView.OnNavigationItemSelectedListener {
            override fun onNavigationItemSelected(item: MenuItem): Boolean {
                var activeFragment: Fragment = BeerListFragment()
                when (item.itemId) {
                    R.id.nav_home -> let {
                        activeFragment = BeerListFragment()
                        return true
                    }
    // similiar for the other two options
                }
                childFragmentManager.beginTransaction()
                    .replace(R.id.fragment_container, activeFragment).commit()
                return true
            }
        })```

The problem seems to be that the ids of the layouts for the fragments are not checked in when() statement. If I pass different from BeerListFragment() in the first line of the onCreate() function, it works, so I think there should be an issue with the setOnNavigationItemSelectedListener.

Is there any other way that I can navigate to the particular fragment? I've tried using actions in the navigation_graph, but I don't think it's necessary because I have a bottom navigation menu.
android navigation bottomnavigationview
1个回答
0
投票

如果使用导航组件,为什么要使用childFragmentManager.beginTransaction().replace(R.id.fragment_container, BeerListFragment()).commit()

如果您使用导航组件,并且希望将BottomNavigationView项目重定向到fragment,则不需要任何代码,只需要在BottomNavigationView菜单项中提供正确的ID。

这里有一个快捷的tutorial为您提供帮助。

© www.soinside.com 2019 - 2024. All rights reserved.