androidandroid-fragmentsandroid-viewpagerandroid-tabs

Add an 'ALL ITEMS' tab along with other dynamically created tabs Android


I am fairly new to android and making a view in which I am populating number of tabs based on an array of names.

I have done that successfully but I want to add an additional tab at the start of my tabs whose title will be All Items.

Here is what I am using for dynamic tabs creation:

private void tabsInit() {
        for (int l = 0; l < internalCat.size(); l++) {
            product_tabs_layout.addTab(product_tabs_layout.newTab().setText(internalCat.get(l)));
        }
        ProductPagerAdapter adapter = new ProductPagerAdapter(getSupportFragmentManager(), product_tabs_layout.getTabCount(), internalCat);
        product_viewpager.setAdapter(adapter);
        product_viewpager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(product_tabs_layout));
        product_tabs_layout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                product_viewpager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                product_viewpager.setCurrentItem(tab.getPosition());
            }
        });
    }

The adapter:

public class ProductPagerAdapter extends FragmentStatePagerAdapter {
    int mNumOfTabs;
    List<String> lstInternalCats;

    public ProductPagerAdapter(@NonNull FragmentManager fm, int mNumOfTabs, List<String> lstInternalCats) {
        super(fm);
        this.mNumOfTabs = mNumOfTabs;
        this.lstInternalCats = lstInternalCats;
    }

    @NonNull
    @Override
    public Fragment getItem(int position) {
        return new ProductsFragment().newInstance(lstInternalCats.get(position));
    }

    @Override
    public int getCount() {
        return mNumOfTabs;
    }
}

This is the output:

enter image description here

What I want is an additional tabs like this:

enter image description here

I have tried to add the tab outside the loop and then passed tabscount+1 to the number of tabs but it gives me error.

java.lang.IndexOutOfBoundsException: Index: 4, Size: 4

Is there a way to do it. Please help.


Solution

  • Above solutions did not work for me.

    I solved it by adding the "ALL" manually as the first element in the the List and then added the remaining items starting from Index = 1;

    This way I got the fist element as ALL tab and rest of them as I wanted.

    Code:

    AtomicInteger index = new AtomicInteger(1);
    internalCat.add(0, "All");
     for (int i = 0; i < array.length(); i++) {
       internalCat.add(index.get(), array.getString(i));
       index.getAndIncrement();
    }