如何切换回选项卡式活动中按下的前一个选项卡

时间:2017-11-29 10:58:58

标签: java android android-tabbed-activity

我有一个标签式活动1到5.如果我从3移动到5然后在后退按下我想从5切换回3,即在背面按下我想要移回上一个标签。请帮忙

2 个答案:

答案 0 :(得分:1)

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

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

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

2.现在你的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();
        }
      }

让我知道它是否有帮助。

答案 1 :(得分:0)

这对我有用:) 它的工作原理完全类似于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);
    }

}