Reputation: 447
I have a viewpager with 3 fragments inside . And inside fragments I have a recyclerview if I click on recyclerview item it shows bottom sheet with some details of that item. 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. Any help is apprecieated.
Upvotes: 1
Views: 1105
Reputation: 3547
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()
}
}
}
})
}
Upvotes: 1
Reputation: 972
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:
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. (when expanded = true and when collapsed = false)
Your PagerAdapter needs to be aware of this variable something like:
boolean sheetVisible = pagerAdapter.get(fragment).isSheetExpanded;
And finally, onBackPressed() of the Activity that holds the ViewPager you should do something like this:
@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!
Upvotes: 1