Search code examples
androidandroid-fragmentsandroid-actionbarandroid-viewpagerandroid-tabs

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


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?


Solution

  • 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.