Reputation: 115
I have a simple fragment with this code:
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
Fragment selectedFragment= null;
switch (menuItem.getItemId()){
case R.id.nav_home:
selectedFragment= new HomeFragment();
setTitle("Beranda");
break;
case R.id.nav_message:
selectedFragment= new MessageFragment();
setTitle("Pesan");
break;
case R.id.nav_transaction:
selectedFragment= new TransactionFragment();
setTitle("Transaksi");
break;
case R.id.nav_profile:
selectedFragment= new ProfileFragment();
setTitle("Profil");
if(sessionLevel.equals("admin")){
setTitle("Admin");
}
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment).commit();
return true;
}
};
Most of the fragment are just some kind of holder for Intent Activity. And the Activity itself doesnt have some fancy code.
The problem is that when i do Intent on Profile menu and then press back, the fragment shown is HomeActivity
but the selected button is Profile
.
I dont know about the other 2 fragment since im not there yet, but probably they do the same thing.
Upvotes: 0
Views: 111
Reputation: 11
public interface IOnBackPressed {
boolean onBackPressed();
}
public class FAQFragment extends Fragment implements IOnBackPressed {
public boolean onBackPressed() {
return false
}
}
@Override
public void onBackPressed(){
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStack();
}
}
Upvotes: 1
Reputation: 1314
You can do this like the following:
@Override
public void onBackPressed() {
super.onBackPressed();
Fragment frag = 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.
Upvotes: 1