我正在尝试在两个fragments
之间移动而不会重新创建它们,因此前一个片段中的数据不会消失。
我试图在互联网上寻找答案,尝试了几个小时,但没有成功。我看了那些链接:
在show()
和hide()
之后,我也尝试了AddToBackStack()
,但没有成功
class MainActivity : AppCompatActivity(){
private val onNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
@Override
when (item.itemId) {
R.id.navigation_home -> {
//replaceFragment(SignInFragment())
supportFragmentManager.beginTransaction().hide(AllEventsFragment()).commit()
supportFragmentManager.beginTransaction().show(SignInFragment()).commit()
return@OnNavigationItemSelectedListener true
}
R.id.navigation_events -> {
//replaceFragment(AllEventsFragment())
supportFragmentManager.beginTransaction().hide(SignInFragment()).commit()
supportFragmentManager.beginTransaction().show(AllEventsFragment()).commit()
if (currentUser.isNotEmpty()) {
updateRecyclerView()
sign_in_error?.visibility = View.INVISIBLE
}
return@OnNavigationItemSelectedListener true
}
}
return@OnNavigationItemSelectedListener false
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
supportFragmentManager.beginTransaction().add(R.id.activity_main, AllEventsFragment(), "2").commit()
supportFragmentManager.beginTransaction().add(R.id.activity_main, SignInFragment(), "1").commit()
val navView: BottomNavigationView = findViewById(R.id.nav_view)
navView.setOnNavigationItemSelectedListener(onNavigationItemSelectedListener)
personInEvent = false
}
结果是片段重叠,而没有在它们之间真正导航的选项。我真的尝试了所有我知道的事情,但是在Internet上都有一些答案,但是没有一个答案可以帮助我解决问题。对于这个令人沮丧的问题,我将不胜感激。
答案 0 :(得分:2)
supportFragmentManager.beginTransaction().hide(AllEventsFragment()).commit()
您每次都会重新创建片段!
调用AllEventsFragment()
等同于new AllEventsFragment()
您需要首先实例化它们 例如, 您的代码必须是这样的,
val fragment1: Fragment = SignInFragment()
val fragment2: Fragment = AllEventsFragment()
var active = fragment1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
supportFragmentManager.beginTransaction().add(R.id.activity_main,fragment2 , "2").commit()
supportFragmentManager.beginTransaction().add(R.id.activity_main, fragment1, "1").commit()
val navView: BottomNavigationView = findViewById(R.id.nav_view)
navView.setOnNavigationItemSelectedListener(onNavigationItemSelectedListener)
personInEvent = false
}
在听众内部
R.id.navigation_home -> {
supportFragmentManager.beginTransaction().beginTransaction().hide(active).show(fragment1).commit();
active = fragment1;
return@OnNavigationItemSelectedListener true
}
R.id.navigation_events -> {
//replaceFragment(AllEventsFragment())
supportFragmentManager.beginTransaction().beginTransaction().hide(active).show(fragment2).commit();
active = fragment2
)
//handle rest of the cases
答案 1 :(得分:0)
看看架构组件,您还可以用旧的方法Android - save/restore fragment state实现这一点 当片段不可见时,其暂停或什至可能被破坏,请使用捆绑软件保存数据。 您想要达到的目标可以使用两个容器来完成,但您实际上不应该