例如
我有底部导航有4个选项卡
当我从A--〉B然后B--〉A然后A--〉B然后B--〉A然后按下后退---〉B - A - B - A
我想要删除此重复项,因此如果我按下返回键,则应为B - A,然后退出应用程序
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();
}
}
2条答案
按热度按时间4dbbbstv1#
您总是将事务添加到backStack,因此如果您按下“返回”按钮,您将返回用户所做的整个导航,这是正常的。
也许您可以尝试将事务添加到backStack
transaction.addToBackStack(null);
,但前提是上面没有相同的片段:fragmentManager.findFragmentByTag(TAG)
.要使用此方法,您必须为要替换的每个不同片段分配一个不同的Tag:
所以,试试这个:
你可以这样调用这个函数:
yeotifhr2#
你实际上在你的
onMenuItemSelect(..)
中创建了一个新的示例,并将每个人都添加到backstack中。所以如果这个fragment-type已经存在,要么删除你的addtoBackStack(null)(这样它就不会被多次添加到backstack中),要么避免每次用户在选项卡之间切换时都创建新的示例,例如通过将片段保存在或者一个以IdRes作为键、以Fragment作为值的HashMap