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

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


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


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();