TabLayout+ViewPager+fragmet对tab标题进行动态增删并排序

主要关键类:


import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.ViewGroup;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.lifecycle.Lifecycle;
import androidx.viewpager2.adapter.FragmentStateAdapter;

public class HomeIndexVPAdapter extends FragmentPagerAdapter {
    private List indexBeans;
    private Context context;
    private String dealDate;
    private String year;
    private String isManual;
    private TargetFragment currentFragment;
    public String TAB_TITLE="tabTitle";

    private Map fragments=new HashMap<>();
    private List titles=new ArrayList<>();
    private List selectedBeans=new ArrayList<>();
    private int id=1;
    private Map IdsMap=new HashMap<>();
    private List preIds=new ArrayList<>();
    public HomeIndexVPAdapter(@NonNull FragmentManager fm, List indexBeans, Context context,String dealDate,String year,String isManual) {
        super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
        this.isManual=isManual;
        this.indexBeans=indexBeans;
        this.context=context;
        this.dealDate=dealDate;
        this.year=year;
        IdsMap.clear();
        preIds.clear();
        titles.clear();
        fragments.clear();
        for (int i = 0; i < indexBeans.size(); i++) {
            if ("1".equals(indexBeans.get(i).getIsShow())){//如果自定义展示,才展示
                titles.add(indexBeans.get(i).getIndexName());
                selectedBeans.add(indexBeans.get(i));
                if(!IdsMap.containsKey(indexBeans.get(i).getIndexName())){//刷新判断是否有新增标题
                    IdsMap.put(indexBeans.get(i).getIndexName(),id++);//这里对应fragment,当tab被删减时,这里不用删减,fragment也一样
                }
                fragments .put(indexBeans.get(i).getIndexName(),getFragment(indexBeans.get(i))) ;//到时候数据拿下来后,可以在这里传入数据,或者看看还有没有别的办法可以传入
            }
        }
    }

    private Fragment getFragment(EmphasisIndexBean indexBean){
        TargetFragment fragment=new TargetFragment();
        Bundle bundle=new Bundle();
        bundle.putSerializable("indexBean",indexBean);
        bundle.putString("dealDate",dealDate);
        bundle.putString("year",year);
        bundle.putString("isManual",isManual);
        fragment.setArguments(bundle);
        return fragment;
    }

    @NonNull
    @Override
    public Fragment getItem(int position) {
        /*if (fragments.containsKey(selectedBeans.get(position).getIndexName())){
            return fragments.get(getPageTitle(position));//返回对应的fragment
        }else {
            TargetFragment fragment=new TargetFragment(context, selectedBeans.get(position), dealDate, year,isManual);
            fragments.put(selectedBeans.get(position).getIndexName(),fragment);
            return fragment;
        }*/
        return fragments.get(getPageTitle(position));//返回对应的fragment
    }

    @Override
    public int getCount() {
        return titles!=null?titles.size():0;
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return titles!=null?titles.get(position):super.getPageTitle(position);
    }


    @Override
    public long getItemId(int position) {
        return IdsMap.size()>0?IdsMap.get(getPageTitle(position)):super.getItemId(position);
    }

    @Override
    public int getItemPosition(@NonNull Object object) {
        TargetFragment fragment= (TargetFragment) object;
        //String title=fragment.getTitle();
        int preId = preIds.indexOf(fragment.getTitle());
        int newId=-1;
        int i=0;
        int size=getCount();
        for(;i

使用:

private void initTabFragment() {
        tabBeans.clear();
        tabTitles.clear();
        if (vpAdapter != null) {
            vpAdapter = null;
        }
        for (int i = 0; i < indexBeans.size(); i++) {
            if ("1".equals(indexBeans.get(i).getIsShow())) {//如果自定义展示,才展示
                tabTitles.add(indexBeans.get(i).getIndexName());
                tabBeans.add(indexBeans.get(i));
            }
        }

        tabTarget.setTabMode(TabLayout.MODE_SCROLLABLE);//这里要特别注意下,如果tab超出了屏幕宽度,设置成fixed,那么tab就不会显示
        //设置监听改变选中字体样式
        tabTarget.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                selectedTab(tab);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                View view = tab.getCustomView();
                if (null != view && view instanceof TextView) {
                    // 改变 tab 未选择状态下的字体大小
                    ((TextView) view).setTextSize(15);
                    // 改变 tab 未选择状态下的字体颜色
                    ((TextView) view).setTextColor(ContextCompat.getColor(context, R.color.tab_nuselect));
                    ((TextView) view).setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));//设置加粗
                    //((TextView) view).setCompoundDrawables(null,null,null, null);
                    ViewUtil.setTViewDrawable(((TextView) view), R.drawable.ic_tab_unselect, ViewUtil.BOTTOM);
                }

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                //selectedTab(tab);
            }
        });

        vpAdapter = new HomeIndexVPAdapter(getChildFragmentManager(), indexBeans, context, dealDate, year, isManual);
        vpTargetInfo.setOffscreenPageLimit(indexBeans.size());//----------------------------------------------------------------------------------------------------------
        vpTargetInfo.setAdapter(vpAdapter);
        tabTarget.setupWithViewPager(vpTargetInfo);
        setTabItem();

        if ((!TextUtils.isEmpty(selectIndexDay) && UserConstant.dateType == 1) | (!TextUtils.isEmpty(selectIndexMon) && UserConstant.dateType == 2)) {//缓存选中的重点指标
            for (int i = 0; i < tabBeans.size(); i++) {
                if (selectIndexDay.equals(tabBeans.get(i).getIndexId()) | selectIndexMon.equals(tabBeans.get(i).getIndexId())) {
                    tabTarget.getTabAt(i).select();//默认选中第一个
                    selectedTab(tabTarget.getTabAt(tabTarget.getSelectedTabPosition()));//选中
                }
            }
        } else {
            if (tabTarget.getTabCount() > 0) {
                tabTarget.getTabAt(0).select();//默认选中第一个
                selectedTab(tabTarget.getTabAt(tabTarget.getSelectedTabPosition()));//选中
            }
        }
    }

    /**
     * 设置tab的item样式
     */
    private void setTabItem() {
        for (int i = 0; i < tabTitles.size(); i++) {
            //tl_video_section.addTab(tl_video_section.newTab());//这样写会出现item数目多出一倍,下面才是正确写法
            //tabTarget.addTab(tabTarget.newTab());//得跟removeAllTabs一起使用
            TabLayout.Tab tab = tabTarget.getTabAt(i);
            if (tab != null) {
                tab.setCustomView(ViewUtil.getTabView(context, i, tabTitles));
            }
        }
    }

    /**
     * 选中改变样式
     *
     * @param tab
     */
    private void selectedTab(TabLayout.Tab tab) {
        // 获取 tab 组件
        View view = tab.getCustomView();
        if (null != view && view instanceof TextView) {
            // 改变 tab 选择状态下的字体大小
            ((TextView) view).setTextSize(16);
            // 改变 tab 选择状态下的字体颜色
            ((TextView) view).setTextColor(ContextCompat.getColor(context, R.color.text_black));
            ((TextView) view).setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));//设置加粗
            ViewUtil.setTViewDrawable(((TextView) view), R.drawable.ic_tab_select, ViewUtil.BOTTOM);
        }
    }

你可能感兴趣的:(TabLayout+ViewPager+fragmet对tab标题进行动态增删并排序)