[英]Close bottom sheet inside fragment from activity
I have a viewpager with 3 fragments inside .我有一个里面有 3 个片段的 viewpager。 And inside fragments I have a recyclerview if I click on recyclerview item it shows bottom sheet with some details of that item.在片段内部,我有一个 recyclerview,如果我点击 recyclerview 项目,它会显示底部的表格,其中包含该项目的一些详细信息。 But when I click back button it closes the app.但是当我点击后退按钮时,它会关闭应用程序。 How can I acheive that if I click back button it will close bottom sheet and then app.如果我点击后退按钮,我怎么能做到这一点,它会关闭底部工作表,然后关闭应用程序。 I can close bottom sheet.我可以关闭底页。 But inside fragment there is no onBackPressed method so I can not.但是在片段内部没有 onBackPressed 方法所以我不能。 Any help is apprecieated.任何帮助表示赞赏。
There is more the one way to achieve this, but I guess it all comes down to this:还有更多的一种方法可以实现这一点,但我想这一切都归结为:
Note: Since there is no code I suspect that the bottom sheet is inside of your fragment.注意:由于没有代码,我怀疑底部工作表在您的片段内。
You have to setBottomSheetCallback to the fragment that you have it in:您必须将BottomSheetCallback 设置为您所在的片段:
BottomSheetBehavior.BottomSheetCallback() {
@Override
public void onStateChanged(@NonNull View view, int newState) {
switch (newState) {
case BottomSheetBehavior.STATE_EXPANDED: {
// sheet expanded
}
break;
case BottomSheetBehavior.STATE_COLLAPSED: {
// sheet collapsed
}
break;
}
}
@Override
public void onSlide(@NonNull View view, float v) {
}
});
Then have a global boolean like isSheetExpanded and set it onStateChanged.然后有一个像 isSheetExpanded 这样的全局布尔值并将其设置为 onStateChanged。 (when expanded = true and when collapsed = false) (展开时 = true 折叠时 = false)
Your PagerAdapter needs to be aware of this variable something like:您的 PagerAdapter 需要知道这个变量,例如:
boolean sheetVisible = pagerAdapter.get(fragment).isSheetExpanded;
And finally, onBackPressed() of the Activity that holds the ViewPager you should do something like this:最后,保存 ViewPager 的 Activity 的 onBackPressed() 你应该做这样的事情:
@Override
public void onBackPressed() {
if (sheetVisible) {
// collapse bottom sheet
} else {
super.onBackPressed();
}
}
Without any code, this should be enough to point you in the right direction.没有任何代码,这应该足以为您指明正确的方向。
Good luck!祝你好运!
YourFragment :你的片段:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requireActivity().onBackPressedDispatcher.addCallback(
this,
object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
when (bottomSheetBehavior.state) {
BottomSheetBehavior.STATE_HALF_EXPANDED -> {
closeBottomSheetFragment()
}
else -> {
isEnabled = false
requireActivity().onBackPressed()
}
}
}
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.