Saturday 7 November 2020

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.



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

No comments:

Post a Comment