我在更改容器中的片段时遇到问题。我有三个导航:Home
,Special offers
,Profile
。在Home
导航中,根据情况可能是fragment1_1
或fragment2_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()
函数。
答案 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()
}
}