Reputation: 640
let me define my problem first:
i have a ViewPager with ActionBar, each page of view pager is a fargment and each page itself got its own buttons to replace current fragment with another one. for example:
we first launch the application and swipe to third tab,here we setTitle using viewPager onTabchanged method and there is no problem , in this page we have buttons and click on them will replace the page with itself by new values(think of 3rd page as main category which shows list of items and buttons like move us to sub categories which is list of items again) so if we press twice the buttons + we came to 3rd page and each time we replaced fragment now we have 3 fragments in backStack! all i want is when onBackButton Pressed actionBar should set the proper title, here is what i tried:
@Override
public void onBackPressed() {
int mFragmentCount = this.getSupportFragmentManager().getBackStackEntryCount();
super.onBackPressed();
if(mFragmentCount != 0)
{
FragmentManager.BackStackEntry backEntry=getSupportFragmentManager().getBackStackEntryAt(mFragmentCount-1);
String str=backEntry.getName(); //the tag of the fragment
mActionBar.setTitle(str);
}
}
but each time i get ArrayOutOfIndex error with for example invalid index 2 is 2 !
any one can help me on this?
thank you!
Upvotes: 0
Views: 639
Reputation: 1
You can try this:
@Override
public void onBackPressed() {
int count = getFragmentManager().getBackStackEntryCount();
if (count < 2) {
super.onBackPressed();
} else {
FragmentManager.BackStackEntry backStackEntry = getFragmentManager().getBackStackEntryAt(count - 2);
mActionBar(backStackEntry.getName());
getFragmentManager().popBackStack();
}
}
Upvotes: 0
Reputation: 7283
The problem is that when you get the value of mFragmentCount you have x fragments in the backstack but after super.onBackPressed(), you have x-1 fragments so the fragment in the location x-1 in the array does not exist.
Upvotes: 1