简体   繁体   English

当我按回来时导航片段的问题

[英]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.

相关问题 在 Android 中使用片段时处理回按 - Handling back press when using fragments in Android 向后按下时碎片会被破坏。 我希望它在后退时不会被破坏,这样我就可以保存片段的状态 - Fragments are getting destroyed when back pressed. I want it to be not destroy when back press so that I can save the states of fragments 返回按碎片 - Back Press on fragments 我正在使用Fragments,当我按下后退按钮时,应用真的崩溃了。 它随机发生 - I'm using Fragments and when I press the back button really fast the app crashes. It happens randomly 导航回 FragmentPagerAdapter -> 片段为空 - Navigating back to FragmentPagerAdapter -> fragments are empty android中的背压碎片问题 - Back press fragments issue in android Android:浏览片段时更改活动标题; 单击返回按钮时带回相同的标题 - Android: Change activity title when navigating fragments; Bring back same titles when back button clicked 从ViewPager中的嵌套片段向后导航 - Navigating back from nested fragments in ViewPager 动作栏和片段出现问题:回到标签页时,应用崩溃 - Problem with the action bar and fragments: the app crashes when go back on a tab 当我按下返回按钮时应用程序没有响应 - Application not responding when i press the back button
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM