关于Activity压后台Fragment重叠的问题 How To Solve? 利用savedInstanceState,记录当前fragment的index override fun onSaveInstanceState(outState: Bundle) { outState.putInt(SAVED_CURRENT_ID, _currentItemIndex) super.o
关于Activity压后台Fragment重叠的问题
How To Solve?
利用savedInstanceState,记录当前fragment的index
override fun onSaveInstanceState(outState: Bundle) {outState.putInt(SAVED_CURRENT_ID, _currentItemIndex)
super.onSaveInstanceState(outState)
}
在onCreate中获取savedInstanceState中的index
companion object {private const val SAVED_CURRENT_ID = "SAVED_CURRENT_ID"
}
private val vb by lazy { ActivityTabkBottomFragmentBinding.inflate(layoutInflater) }
private var _currentItemIndex = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(vb.root)
savedInstanceState?.let {
_currentItemIndex = savedInstanceState.getInt(SAVED_CURRENT_ID)//从savedInstanceState中获取index
}
...
}
最后塞给adapter
/*** 实例化以及显示指定位置的fragment
* @param container View
* @param position Int
*/
fun instantiateItem(container: View, position: Int) {
val currentTransaction: FragmentTransaction = _fragmentManager.beginTransaction()
if (_currentFragment != null) {
currentTransaction.hide(_currentFragment!!)
}
val name = container.id.toString() + ":" + position
var fragment: Fragment? = _fragmentManager.findFragmentByTag(name)
if (fragment != null) {
currentTransaction.show(fragment)
} else {
fragment = getItem(position)
if (fragment != null && !fragment.isAdded) {
currentTransaction.add(container.id, fragment, name)
}
}
_currentFragment = fragment
currentTransaction.commitAllowingStateLoss()
}