How To Get Last Fragment Used When Pressing Back Button
I have a simple fragment with this code: private BottomNavigationView.OnNavigationItemSelectedListener navListener = new BottomNavigationView.OnNavigationItemSelectedLi
Solution 1:
You can do this like the following:
@OverridepublicvoidonBackPressed() {
super.onBackPressed();
Fragmentfrag= YourActivity.this.getSupportFragmentManager().findFragmentById(R.id.fragment_container);
if(frag!=null && frag instanceof yourFragment)
{}
}
The following will give you count
int count = getSupportFragmentManager().getBackStackEntryCount();
You can make condition, If count is great than 1 then have more than 1 fragments else you have atleast 1 fragment and that will be last fragment. If count 0 then no more fragment available on stack as all have been poped out of stack.
Solution 2:
- Create an interface:
publicinterfaceIOnBackPressed {
booleanonBackPressed();
}
- In Fragment implement IOnBackPressed like:
publicclassFAQFragmentextendsFragmentimplementsIOnBackPressed {
publicbooleanonBackPressed() {
returnfalse
}
}
- On Main Activity Backpress use
@OverridepublicvoidonBackPressed(){
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStack();
}
}
Post a Comment for "How To Get Last Fragment Used When Pressing Back Button"