Haseeb Fazal Haseeb Fazal - 14 days ago 8
reST (reStructuredText) Question

Dynamically adding tabs from webservice

I would like to know the best practice for adding tabs on an android activity, where the number of tabs and it's id are coming from a webservice. For instance, on my Activity I will call a webservice to get the list of categories (which can be of any number), after that the categories will become the tabs on the activity.

I know how to use tabs using fragments, but when I dynamically get the data, I am confused on how to implement this practice.

Regards.

Answer

Use this to add to the tablayout

TabLayout tabLayout = (TabLayout)findViewById(R.id.yourTabLayout);
tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));

to remove use

 tabLayout.removeTabAt(position);

to get a tab use

 tabLayout.getTabAt (position);