How to dynamically set number of swipeable tabs in

2019-05-28 23:25发布

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?

2条回答
手持菜刀,她持情操
2楼-- · 2019-05-29 00:08

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 Fragments. 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 Fragments in the constructor of TabsPagerAdapter:

TabsPagerAdapter adapter = new TabsPagerAdapter(fm, list);

Try this. This will work.

查看更多
The star\"
3楼-- · 2019-05-29 00:14

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);
查看更多
登录 后发表回答