I am referring this link for swipeable tabs using fragments. It worked for me, but what if I need to add the number of tabs dynamically and not pre assign the number of tabs? For instance, some of my logic gives me output at times 2 strings in anarray and at times 4 strings in an array. And according to the logic I need to set the number of tabs in action bar at runtime. How can I achieve this? Can anyone show me how to achieve what I need?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
STEP 1:
Define your TabsPagerAdapter
as follows:
public class TabsPagerAdapter extends FragmentPagerAdapter {
private ArrayList<Fragment> list;
public TabsPagerAdapter(FragmentManager fm, ArrayList<Fragment> list) {
super(fm);
this.list = list;
}
@Override
public Fragment getItem(int index) {
return list.get(index);
}
@Override
public int getCount() {
return list.size();
}
}
STEP 2:
When you determine the number of tabs at runtime, first make sure to create a List
of the required number of Fragment
s. You can do it using either this:
ArrayList<Fragment> list = new ArrayList<Fragment>();
for(int i = 0; i < tabcount; i++){
list.add(MyFragment.newInstance());
}
OR this:
ArrayList<Fragment> list = new ArrayList<Fragment>();
list.add(new GamesFragment());
list.add(new TopRatedFragment());
list.add(new MoviesFragment());
STEP 3:
When you create an Adapter
for the ViewPager
, pass the ArrayList
of Fragment
s in the constructor of TabsPagerAdapter
:
TabsPagerAdapter adapter = new TabsPagerAdapter(fm, list);
Try this. This will work.
回答2:
In your Adapter
make method addTab
, something like:
private final ArrayList<TabInfo> tabs = new ArrayList<TabInfo>();
public void addTab(String tabName, Class<?> clss, Bundle args)
{
TabInfo info = new TabInfo(clss, tabName);
tabs.add(info);
notifyDataSetChanged();
}
... ...
static final class TabInfo
{
private final Class<?> clss;
private final String title;
TabInfo(Class<?> _class, String _title)
{
clss = _class;
title = _title;
}
and your method getCount
:
@Override
public int getCount(){
return tabs.size();
}
all your fragments/tabs should be added by addTab
:
mAdapter.addTab(getResources().getString(R.string.tab_name), YourFragment.class, null);