[英]Problem with navigating fragments when i press on back
Have a fragment in which I display the recyclerView
list. 有一个片段,其中显示了recyclerView
列表。 When I click on a list item in MainActivity
I call the method: 当我在MainActivity
单击列表项时,将调用该方法:
fun FragmentActivity?.replaceFragment(fragment: Fragment): Boolean {
if (this == null) return false
try {
supportFragmentManager?.beginTransaction()?.replace(
R.id.container, fragment,
fragment.createTagName()
)?.commit()
} catch (ignored: IllegalStateException) {
return false
}
return true
}
After this I press the system back button and I have a duplicate list. 之后,我按系统后退按钮,我有一个重复的列表。
Also i have in my MainActivity
next fun: 我也可以在MainActivity
下一个乐趣:
override fun onBackPressed() {
val onBackPressListener = currentFragmentInContainer() as? OnBackPressListener
if (onBackPressListener?.onBackPress() != true) {
super.onBackPressed()
}
}
The issue is you have not added the current fragment to the back stack. 问题是您尚未将当前片段添加到后堆栈中。 In order to get to the starting point, you have to mark the fragment. 为了到达起点,您必须标记片段。 addToBackStack(tag:String)
will help you to do that. addToBackStack(tag:String)
将帮助您做到这一点。
Code: 码:
fun FragmentActivity?.replaceFragment(fragment: Fragment): Boolean {
if (this == null) return false
try {
supportFragmentManager?.beginTransaction()?.replace(
R.id.container, fragment,
fragment.createTagName()
).addToBackStack(fragment.createTagName())?.commit()
} catch (ignored: IllegalStateException) {
return false
}
return true
}
Here is the documentation about the method : addToBackStack 这是有关该方法的文档: addToBackStack
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.