javaandroidandroid-layouttabspagerslidingtabstrip

Add and Remove Tabs from TabLayout


Guys I have three tabs in my layout, in another activity, I have a multichoice dialog box to select the tabs that I want to be visible or not in my layout but I am not able to understand how I can remove and add tabs and fragments from my layout

public class TabAdapter extends FragmentStatePagerAdapter {


private String[] tituloTabs = {"X","Y","Z"};



public TabAdapter(@NonNull FragmentManager fm) {
    super(fm);
}



@NonNull
@Override
public Fragment getItem(int position) {

    Fragment fragment = null;
    switch (position){
        case 0 :
            fragment = new XFragment();
                break;
        case 1 :
            fragment = new YFragment();
                break;

        case 2:
            fragment = new ZFragment();
                break;
    }
    return fragment;
}

@Override
public int getCount() {
    return tituloTabs.length;
}


@Nullable
@Override
public CharSequence getPageTitle(int position) {
    return tituloTabs[position];
}

Activity Code

 SlidingTabLayout slidingTabLayout = findViewById(R.id.stl_tabs);
    viewPager =  findViewById(R.id.vp_pagina);
    viewPager.setPageTransformer(true,new ZoomOutPageTransformer());


    //---------------------------Configurar Sliding Tab--------------------------------------

    slidingTabLayout.setSelectedIndicatorColors(ContextCompat.getColor(this,R.color.colorPrimary));
    slidingTabLayout.setDistributeEvenly(true);
    slidingTabLayout.setBackgroundColor( ContextCompat.getColor( this, R.color.black ) );

    //-----------------------------Configurar Adapter ----------------------------------------
    TabAdapter tabAdapter = new TabAdapter(getSupportFragmentManager());
    viewPager.setAdapter(tabAdapter);

    slidingTabLayout.setViewPager(viewPager);

Solution

  • I managed to find a solution to my problem, replaced the arrays with ArrayList and implemented the methods to add an remove Fragment and Title in this way

    public TabAdapter(FragmentManager fm) {
        super(fm);
    }
    
    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }
    
    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }
    
    public void removeitem(int position){
        mFragmentList.remove(position);
    
    }
    
    public void removetitle(int position){
    
        mFragmentTitleList.remove(position);
    }
    
    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
    
    @Override
    public int getCount() {
        return mFragmentList.size();
    }
    @Override
    public int getItemPosition(Object object){
        return PagerAdapter.POSITION_NONE;
    }}