使用底部导航栏管理片段

时间:2019-11-20 06:38:38

标签: android android-fragments

我在更改容器中的片段时遇到问题。我有三个导航:HomeSpecial offersProfile。在Home导航中,根据情况可能是fragment1_1fragment2_2。我的问题是从容器中显示碎片。我尝试使用findFragmentById,但是当我进入Profile导航并尝试转到Home时,我的代码却没有hide()来自Pofile的片段。我试图查看日志,但发现它隐藏了Home并显示了Home。我的导航代码:

botNav.setOnNavigationItemSelectedListener {
        when(it.itemId){
            R.id.act_home -> {
                if (!it.isChecked){
                    val homeFragment = supportFragmentManager.findFragmentByTag("Home")
                    activeFragment = supportFragmentManager.findFragmentById(R.id.fragment_container)
                    activeFragment?.let { hideFragment(it) }
                    showFragment(homeFragment!!)
                }
            }
            R.id.act_profile_info -> {
                if (!it.isChecked) {
                    activeFragment = supportFragmentManager.findFragmentById(R.id.fragment_container)
                    activeFragment?.let { hideFragment(it) }
                    showFragment(profileFragment)
                }
            }
            R.id.act_special_offer -> {
                if (!it.isChecked) {
                    activeFragment = supportFragmentManager.findFragmentById(R.id.fragment_container)
                    activeFragment?.let { hideFragment(it) }
                    showFragment(specialFragment)

                }
            }
        }
        return@setOnNavigationItemSelectedListener true
    }

所以现在我想了解为什么这样做,以及如何从FrameLayout容器中显示片段。 为了为导航添加片段,我使用了addFragment()函数。

2 个答案:

答案 0 :(得分:0)

您可以尝试以下一种方法:

            //Fragment1 is your new fragment to be shown.
            Fragment fragment=new Fragment1();
            if (fragment != null) {
                FragmentTransaction ft=getSupportFragmentManager().beginTransaction();
                //frams is your backup fragment upon on your navigation/new black 
                fragment(thi will beshown if the Fragment1 is not working)
                ft.replace(R.id.frams, fragment);
                ft.commit();

答案 1 :(得分:0)

您可以尝试一下。经过测试,对我来说一切正常。

每当要添加并显示先前的现有片段时,调用此波纹管方法

 /**
 * Method for add and replace and set fragment if exist in stack
 */
fun setAndReplaceFragment(fragmentWantToAdd: Fragment, tag: String) {
    val manager = supportFragmentManager
    val fragmentFind = manager.findFragmentByTag(tag)
    if (fragmentFind != null) {
        val ft = manager.beginTransaction()
        ft.replace(R.id.mFrmContainer, fragmentFind, tag)
        ft.addToBackStack(tag)
        ft.commit()
    } else {
        val ft = manager.beginTransaction()
        ft.replace(R.id.mFrmContainer, fragmentWantToAdd, tag)
        ft.addToBackStack(tag)
        ft.commit()
    }
}