for Ex.
I have bottom navigation have 4 tab
when I navigate from A-->B then B-->A then A-->B then B-->A THEN press back ---> B - A - B - A
What I want remove this duplicate so if I press back should be B - A then exit app
public class MainActivity extends BaseActivity implements BottomNavigation.OnMenuItemSelectionListener {
private BottomNavigation mBottomNavigation;
private List<Integer> openedTabs = new ArrayList<>();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeViewComponents();
}
private void initializeViewComponents() {
mBottomNavigation = (BottomNavigation) findViewById(R.id.BottomNavigation);
if (null != mBottomNavigation) {
if (openedTabs.size() == 0) {
openedTabs.add(0);
}
mBottomNavigation.setDefaultSelectedIndex(0);
mBottomNavigation.setOnMenuItemClickListener(this);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_my_contacts, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.menu_contacts_search) {
}
return false;
}
@Override
public void onBackPressed() {
super.onBackPressed();
if (openedTabs.size() > 0) {
int lastIndex = openedTabs.size() - 1;
int beforeTheCurrent = lastIndex - 1;
if (beforeTheCurrent >= 0) {
mBottomNavigation.setSelectedIndex(openedTabs.get(beforeTheCurrent), true);
printLog("OnBackPressed", "Size: " + openedTabs.size() + " ---> LastIndex: " + lastIndex + " ---> Current: " + openedTabs.get(lastIndex) + "Go To: " + openedTabs.get(beforeTheCurrent));
openedTabs.remove(lastIndex);
}
}
}
@Override
public void onMenuItemSelect(@IdRes int i, int i1) {
openedTabs.add(i1);
switch (i) {
case R.id.profile:
printLog("Item", "profile");
replaceFragment(new ProfileFragment());
break;
case R.id.my_contacts:
printLog("Item", "my_contacts");
replaceFragment(new MyContactsFragment());
break;
case R.id.requests:
printLog("Item", "requests");
replaceFragment(new RequestsFragment());
break;
case R.id.settings:
printLog("Item", "settings");
replaceFragment(new SettingsFragment());
break;
}
}
@Override
public void onMenuItemReselect(@IdRes int i, int i1) {
}
private void replaceFragment(Fragment fragment) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.fragmentContainer,fragment);
transaction.addToBackStack(null);
transaction.commit();
}
}