Dynamically add and remove tabs in TabLayout(material design) android

不问归期 提交于 2019-11-28 17:12:36

Remove tab from TabLayout

...
public void removeTab(int position) {
    if (mTabLayout.getTabCount() >= 1 && position<mTabLayout.getTabCount()) {
          mTabLayout.removeTabAt(position);
          mPagerAdapter.removeTabPage(position);
    }
}
...

Add a removeTabPage method to your PagerAdapter

...
public void removeTabPage(int position) {
    if (!tabItems.isEmpty() && position<tabItems.size()) {
          tabItems.remove(position);
          notifyDataSetChanged();
    }
}
...

Add a Tab

...
private void addTab(String title) {
        mTabLayout.addTab(mTabLayout.newTab().setText(title));
        mPagerAdapter.addTabPage(title);
}
...

Add a addTabPage method to your PagerAdapter

...
public void addTabPage(String title) {
      tabItems.add(title);
      notifyDataSetChanged();
}
...

Check out this sample code for a full example: ...samples/SupportDesignDemos/src/com/example/android/support/design/widget/TabLayoutUsage.java

MidasLefko

With the new support library (I'm using 23.2.1) you should only add to the Viewpager and not the TabLayout (otherwise you end up with double tabs and other funky behavior). So to update TouchBoarder's answer:

Add a removeTabPage method to your PagerAdapter

public void removeTabPage(int position) {
    if (!tabItems.isEmpty() && position<tabItems.size()) {
          tabItems.remove(position);
          notifyDataSetChanged();
    }
}

Add a addTabPage method to your PagerAdapter

public void addTabPage(String title) {
      tabItems.add(title);
      notifyDataSetChanged();
}

In addition to existing answers, to remove all tabs from tabLayout.

tabLayout.removeAllTabs();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!