主要重写onSaveInstanceState保存Fragment,切换后进行赋值
1.定义四个Fragment。在切换深色\浅色模式时会重新创建内存
private var aFragment:Fragment? = null
private var bFragment:Fragment? = null
private var cFragment:Fragment? = null
private var dFragment:Fragment? = null
2.在onCreate里面进行判断是第一次进入还是重新绘制
override fun onCreate(savedInstanceState: Bundle?) {
。。。
if(savedInstanceState == null){ // 判断是否是第一次绘制Activity
// 设置默认页面
replaceZhanTingPageFragment()
// 更改默认页面的Icon为b页的对应icon
binding.bottomNavigationView.selectedItemId = binding.bottomNavigationView.menu.getItem(1).itemId
}else{
// 如果切换了深色/浅色模式 将之前存放的fragment状态赋予新创建的Fragment
aFragment= supportFragmentManager.getFragment(savedInstanceState,"aFragmentBundle")
bFragment= supportFragmentManager.getFragment(savedInstanceState,"bFragmentBundle")
cFragment= supportFragmentManager.getFragment(savedInstanceState,"cFragmentBundle")
dFragment= supportFragmentManager.getFragment(savedInstanceState,"dFragmentBundle")
}
initView()
。。。
}
3.每次绘制都要进行赋值按钮
private fun initView(){
binding.bottomNavigationView.setOnItemSelectedListener(NavigationBarView.OnItemSelectedListener { item ->
val id = item.itemId
when (id) {
R.id.a-> replaceA()
R.id.b-> replaceB()
R.id.c-> replaceC()
R.id.d-> replaceD()
}
true
})
}
4.四个初始化Fragment页面。防止重新创建布局重叠
private fun replaceA {
val transaction = supportFragmentManager.beginTransaction()
if(aFragment == null){
aFragment = AFragment()
transaction.add(R.id.framelayout_container,
aFragment as AFragment, "aFragment")
}
hideFragment(transaction)
transaction.show(aFragment!!)
transaction.commit()
}
private fun replaceB {
val transaction = supportFragmentManager.beginTransaction()
if(bFragment == null){
bFragment = BFragment()
transaction.add(R.id.framelayout_container,
bFragment as BFragment, "bFragment")
}
hideFragment(transaction)
transaction.show(bFragment!!)
transaction.commit()
}
private fun replaceC {
val transaction = supportFragmentManager.beginTransaction()
if(cFragment == null){
cFragment = CFragment()
transaction.add(R.id.framelayout_container,
cFragment as CFragment, "cFragment")
}
hideFragment(transaction)
transaction.show(cFragment!!)
transaction.commit()
}
private fun replaceD {
val transaction = supportFragmentManager.beginTransaction()
if(dFragment == null){
dFragment = DFragment()
transaction.add(R.id.framelayout_container,
dFragment asDFragment, "dFragment")
}
hideFragment(transaction)
transaction.show(dFragment!!)
transaction.commit()
}
5.隐藏所有的fragment
private fun hideFragment(transaction: FragmentTransaction) {
if (aFragment != null) {
transaction.hide(aFragment!!)
}
if (bFragment != null) {
transaction.hide(bFragment!!)
}
if (cFragment != null) {
transaction.hide(cFragment!!)
}
if dFragment != null) {
transaction.hide(dFragment!!)
}
}