I am using a ViewPager to implement swiping in my android app. However, I would like the previous fragment to be shown when the user uses the back button instead of ending t
I have same issue and i follow this step (Edited my answer--- Certainly work for me, give it a try)
In the main activity where there are 3 fragment in viewpager i create stack and push and pop data.
private Stack stackkk;
private ViewPager mPager;
private int tabPosition = 0;
mTabLayout.setupWithViewPager(mPager);
mPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout));
mTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
tabPosition = tab.getPosition();
mPager.setCurrentItem(tab.getPosition());
// here i have add the data into the stack in each tab click, as at first it will always be null so i add 0 position
if (stackkk.empty())
stackkk.push(0);
if (stackkk.contains(tabPosition)) {
stackkk.remove(stackkk.indexOf(tabPosition));
stackkk.push(tabPosition);
} else {
stackkk.push(tabPosition);
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
tabPositionUnselected = tab.getPosition();
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
and in the onBackPressed in activity,
//OnbackPress i have first taken out the last one as it already and
//selected by poping it out then only set to the pager.
@Override
public void onBackPressed() {
if (stackkk.size() > 1) {
stackkk.pop();
mPager.setCurrentItem(stackkk.lastElement());
} else {
}
}
Hope this may help or msg me.