How to dynamically set number of swipeable tabs in Action Bar with Fragments at runtime

僤鯓⒐⒋嵵緔 提交于 2019-12-08 03:00: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?


回答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 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.




回答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);


来源:https://stackoverflow.com/questions/28676491/how-to-dynamically-set-number-of-swipeable-tabs-in-action-bar-with-fragments-at

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