基础知识,如何拿到java的修饰符:
https://blog.csdn.net/xiao__gui/article/details/8141216
解决重叠的第四种方法:
https://www.2cto.com/kf/201606/518375.html
-
我们判断一下
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)//这里我们将管理四个Fragment; if(savedInstanceState!=null){ //这里肯定保存了fragments; getFragmentsFromManager(); showFragment(0) }else{ initData(); } initListener();
}
/**
- 从FragmentManagers里面获取Fragment;
*/
private fun getFragmentsFromManager() {
arrayList.add(supportFragmentManager.findFragmentByTag(FRAGMENT_TAG_HOME))
arrayList.add(supportFragmentManager.findFragmentByTag(FRAGMENT_TAG_CART))
arrayList.add(supportFragmentManager.findFragmentByTag(FRAGMENT_TAG_MSG))
arrayList.add(supportFragmentManager.findFragmentByTag(FRAGMENT_TAG_USER))
}
/**
-
构建所有的Fragments;
*/
private fun initFragments() {var beginTransaction = supportFragmentManager.beginTransaction()
var homeFragment = HomeFragment()
var cartFragment = CartFragment()
var messageFragment = MessageFragment()
var userFragment = UserFragment()arrayList.add(homeFragment)
arrayList.add(cartFragment)
arrayList.add(messageFragment)
arrayList.add(userFragment)
//这里我们要做的一个就是;beginTransaction.add(R.id.mFragmentContainer,homeFragment,FRAGMENT_TAG_HOME);
beginTransaction.add(R.id.mFragmentContainer,cartFragment,FRAGMENT_TAG_CART);
beginTransaction.add(R.id.mFragmentContainer,messageFragment,FRAGMENT_TAG_MSG);
beginTransaction.add(R.id.mFragmentContainer,userFragment,FRAGMENT_TAG_USER);beginTransaction.commitAllowingStateLoss();
}
- 从FragmentManagers里面获取Fragment;
-
第五种方法:这里是系统提供的一个方法供实现的一个操作;
@Override public void onAttachFragment(Fragment fragment) { if (tab1 == null && fragment instanceof Tab1Fragment) tab1 = fragment; if (tab2 == null && fragment instanceof Tab2Fragment) tab2 = fragment; if (tab3 == null && fragment instanceof Tab3Fragment) tab3 = fragment; if (tab4 == null && fragment instanceof Tab4Fragment) tab4 = fragment; }
上面这个方法的可行之处在于,系统在恢复Fragment的时候,会将Fragment重新添加到FragmentManager里面,然后会onAttachFragment这个方法,将对应的Fragment暴露出来,避免了重新new 一个Fragment,从而造成的重影的现象;
上面所有的方法的思路大致都是将onSaveInstance里面的Fragments复用起来,避免重新创建与添加