如何在选项卡 activity 中按下后切换回上一个选项卡

How to switch back to previous tab on back pressed in an tabbed activity

我有一个选项卡 activity 1 到 5。如果我从 3 移到 5,然后按下后退键,我想从 5 切换回 3,即按下后退键,我想回到上一个标签。请帮助

使用以下代码实现。(代码也经过测试。)

1.Initialise 一个整数列表和一个布尔值;

private boolean isBackPressed = false;  
private boolean isBackPressedOnce = false;   
private List<Integer> tabsInBack = new ArrayList<>();

2.Now 你的 onTabSelectedListener 必须像

tabs.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
      @Override
      public void onTabSelected(TabLayout.Tab tab) {
        if(!isBackPressed){
          tabsInBack.add(tab.getPosition());}
        else {
              isBackPressed = false;}              
      }

      @Override
      public void onTabUnselected(TabLayout.Tab tab) {

      }

      @Override
      public void onTabReselected(TabLayout.Tab tab) {

      }
    });

3(i)。现在你的 onBackPressed() 函数必须是,(一个选项卡返回然后关闭)

    @Override
      public void onBackPressed() {
        isBackPressed = true;
        if (tabsInBack != null && tabsInBack.size() > 0) {
          if (tabs.getSelectedTabPosition() == tabsInBack.get(tabsInBack.size() - 1)) {
            tabsInBack.remove(tabsInBack.size() - 1);

          }
          if (tabsInBack != null && tabsInBack.size() > 0) {
            tabs.getTabAt(tabsInBack.get(tabsInBack.size() - 1)).select();
            tabsInBack.remove(tabsInBack.size() - 1);

          } else {
            super.onBackPressed();
          }
        } else {
          super.onBackPressed();
        }
      }

3(ii)。现在您的 onBackPressed() 函数必须是,(返回所有选定的选项卡然后关闭)

    @Override
      public void onBackPressed() {
        isBackPressed = true;
        if (tabsInBack != null && tabsInBack.size() > 0) {
          if (tabs.getSelectedTabPosition() == tabsInBack.get(tabsInBack.size() - 1)) {
            tabsInBack.remove(tabsInBack.size() - 1);

          }
          if (tabsInBack != null && tabsInBack.size() > 0) {
            tabs.getTabAt(tabsInBack.get(tabsInBack.size() - 1)).select();
            tabsInBack.remove(tabsInBack.size() - 1);
             if(isBackPressedOnce )
               {
                 super.onBackPressed();
               }
            else
               {
                 isBackPressedOnce = true;
               }
          } else {
            super.onBackPressed();
          }
        } else {
          super.onBackPressed();
        }
      }

让我知道它是否有帮助。

这对我有用:) 它的工作原理与 whatsapp

完全一样

@Override public void onBackPressed() {

    //If first tab is open, then quit
    if (viewPager.getCurrentItem() == 0) {

        super.onBackPressed();
    }else {

        //If any other tab is open, then switch to first tab
        viewPager.setCurrentItem(0);
    }

}