I have created an android app (Sample APK & Github Repo) where I implement a BottomNavigationBar
with ViewPager
. Navigation is ok but I don't know how to handle the back stack in a viewpager like Instagram.
I tried the below code but this way I have to create an unnecessary fragment where I never navigate.
view_pager_main_activity?.currentItem = view_pager_main_activity.currentItem - 1
suppose I just launch the app to the 1st page and then navigate to the 3rd page by BottomNavBar but now if I click the back button, I go back to the 1st page through the 2nd page. So this way I create the unwanted 2nd page.
Here is the whole back stack process onBackPressed()
override fun onBackPressed() {
if (view_pager_main_activity?.currentItem == 0) {
if (view_pager_main_fragment?.currentItem == 0) {
val recyclerView = findViewById<RecyclerView>(R.id.listRecyclerView)
val appbarHome = findViewById<AppBarLayout>(R.id.appbar_home)
val layoutManager = recyclerView?.layoutManager as LinearLayoutManager
when {
layoutManager.findFirstCompletelyVisibleItemPosition() == 0 -> {
super.onBackPressed()
}
supportFragmentManager.backStackEntryCount != 0 -> {
supportFragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
}
else -> {
layoutManager.scrollToPositionWithOffset(0, 0)
appbarHome.setExpanded(true)
}
}
} else if (supportFragmentManager.backStackEntryCount != 0) {
super.onBackPressed()
} else {
view_pager_main_fragment?.setCurrentItem(
view_pager_main_fragment.currentItem - 1,
false
)
}
} else if (supportFragmentManager.backStackEntryCount != 0) {
super.onBackPressed()
} else {
view_pager_main_activity?.currentItem = view_pager_main_activity.currentItem - 1
}
}
I want back stack navigation as same as Instagram so I tried this way but has deprecated. I don't know how can I achieve that.