ViewPager Fragment navigation On Back button, (same as instagram navigation)
While navigating through tabs we want our navigation should be remember by the app, and we should be navigate back in the reverse sequence of how we visited Fragments. once we revisit same fragment , old instance get removed from the sequence as we already seen it recently. same as Instagram navigation.
I have integrated viewPager inside Fragment , your might be on Activity, if so you are geting onBackPressed() method when click on back button, I have used onBackPressedDispatcher.addCallback instead. So you can copy code from onBackPressedDispatcher.addCallback to onBackPressed()
Initialize below properties
val pageHistory = Stack<Int>()
var saveToHistory = false
var viewPager: ViewPager? = null
Add below code in onCreateView() of Fragment, if you are using Activity then in onCreate()
viewPager = root.findViewById(R.id.viewPager)
pageHistory.push(0);
viewPager?.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
override fun onPageScrolled(
position: Int,
positionOffset: Float,
positionOffsetPixels: Int,
) {
}
override fun onPageSelected(position: Int) {
if (saveToHistory) {
if (pageHistory.contains(position)) {
pageHistory.remove(position)
pageHistory.push(position);
} else {
pageHistory.push(position);
}
}
}
override fun onPageScrollStateChanged(state: Int) {
}
})
saveToHistory = true;
Add below code in OnCreateView() , or if you are using activity below code will come inside onBackPressed() instead of onBackPressedDispatcher.addCallback
requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner) {
// Handle the back button event
if (pageHistory.size > 1) {
saveToHistory = false;
pageHistory.pop()
viewPager?.currentItem = pageHistory.peek()
saveToHistory = true;
} else {
if(pageHistory.size ==1){
pageHistory.pop()
}
if (viewPager?.currentItem == 0){
requireActivity().finish()
}else{
viewPager?.currentItem = 0
}
}
}
onBackPressedDispatcher.addCallback is to get callback on back button press in Fragment.
This is how you can add navigation of fragment for ViewPager
Thank you!