简体   繁体   English

条件成立时如何在片段中实现特定的后退按钮功能,否则使用默认的后退按钮功能?

[英]How to implement specific back button functionallity in fragment when condition is made and use default back button functionallity otherwise?

I want to clear selection on back button pressed on selection tracker when there are selected items and use default back button functionallity if there are no selected items.我想在有选定项目时清除选择跟踪器上按下的后退按钮上的选择,如果没有选定项目,我想使用默认的后退按钮功能。

I use Navigation Components for working with fragments.我使用导航组件来处理片段。

Code in my fragment which implements OnBackPressedListener interface:我的片段中实现 OnBackPressedListener 接口的代码:

override fun onBackPressed() {
    if (tracker?.hasSelection() == true) tracker?.clearSelection()
    else findNavController().popBackStack()
}

Clear selection condition is working, but else block does not.清除选择条件有效,但其他块无效。

Code from my BaseActivity which determines how to use back button.我的 BaseActivity 中的代码确定如何使用后退按钮。

override fun onBackPressed() {
    val currentFragment = navHost.childFragmentManager.fragments[0]
    if (currentFragment is OnBackPressedListener) {
        currentFragment.onBackPressed()
    } else {
        super.onBackPressed()
    }
}

So, question is how to exit fragment (or pop backstack) when there are no selected items in selection tracker?因此,问题是在选择跟踪器中没有选定的项目时如何退出片段(或弹出背板)? It is working when I call当我打电话时它正在工作

requireActivity().finish() 

, but I do not know if this is correct solution. ,但我不知道这是否是正确的解决方案。

For this case, you could try registering OnBackPressedCallback on your Fragments via addOnBackPressedCallback.对于这种情况,您可以尝试通过 addOnBackPressedCallback 在 Fragments 上注册 OnBackPressedCallback。 For more detail follow the below-given link:有关更多详细信息,请点击以下链接:

https://developer.android.com/guide/navigation/navigation-custom-back https://developer.android.com/guide/navigation/navigation-custom-back

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM