TabLayout+ViewPager2的联合使用

Posted kaolagirl

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了TabLayout+ViewPager2的联合使用相关的知识,希望对你有一定的参考价值。

android项目开发中,点击文字标签可以切换到相对应的内容的这种需求还是很常见的,实现效果看下图。

下面的话就来介绍下两种方式,第一种的话是我最初的时候自己自定义的,直至发现了TabLayout这个控件,然后就转用了TabLayout+ViewPager2,虽然第一种不用了但还是想把它记录下来。

一. 自定义tab标题栏+ViewPager2实现

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".mime.order.my_order.MyOrder"
    android:orientation="vertical">
    <include layout="@layout/classify_head" /> //标题栏
    <LinearLayout     //tab文字标签栏
        android:id="@+id/tab_container"
        android:layout_gravity="top"
        android:background="@drawable/order_tab_default_border"
        android:paddingRight="6dp"
        android:paddingLeft="6dp"
        android:gravity="center_vertical"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="40dp">
        <TextView
            android:id="@+id/tab1"
            android:text="全部"
            android:textColor="@drawable/order_tab_tv"
            android:gravity="center"
            android:layout_weight="1.0"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"/>
        <TextView
            android:id="@+id/tab2"
            android:text="待付款"
            android:textColor="@drawable/order_tab_tv"
            android:gravity="center"
            android:layout_weight="1.0"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"/>
        <TextView
            android:id="@+id/tab3"
            android:text="待发货"
            android:textColor="@drawable/order_tab_tv"
            android:gravity="center"
            android:layout_weight="1.0"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"/>
        <TextView
            android:id="@+id/tab4"
            android:text="待收货"
            android:textColor="@drawable/order_tab_tv"
            android:gravity="center"
            android:layout_weight="1.0"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"/>
        <TextView
            android:id="@+id/tab5"
            android:text="已完成"
            android:textColor="@drawable/order_tab_tv"
            android:gravity="center"
            android:layout_weight="1.0"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"/>
    </LinearLayout>
    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/myOrder_vp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>
public class MyOrder extends AppCompatActivity implements View.OnClickListener{
    private static final String TAG = "春加福";
    private ViewPager2 myOrder_vp;
    private List<Fragment> list = new ArrayList<>();
    private TextView tab1,tab2,tab3,tab4,tab5,tab_current;
    private LinearLayout head_search;
    private TextView default_tv;
 
    private int order_code;
    private  String txt;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_order);
        if(getIntent() !=null){
            order_code = getIntent().getIntExtra("order_code",0);
            txt = getIntent().getStringExtra("txt");
        }

        initView();
        initTab();
    }


    /**
     * todo initView 初始化控件
     */
    private void initView() {
        tab1 = findViewById(R.id.tab1);
        tab2 = findViewById(R.id.tab2);
        tab3 = findViewById(R.id.tab3);
        tab4 = findViewById(R.id.tab4);
        tab5 = findViewById(R.id.tab5);
       
        myOrder_vp  = findViewById(R.id.myOrder_vp);
        head_search = findViewById(R.id.head_search);

        //wang添加 2021/7/13
        default_tv = findViewById(R.id.default_tv);
        default_tv.setText("搜索订单");
        default_tv.setVisibility(View.VISIBLE);

        head_search.setOnClickListener(this);

        initPager();
    }

    /**
     * todo initTab 初始化 顶部导航栏,并设置点击监听
     */
    private void initTab() {
        switch (txt.toString()){
            case "全部":
                Log.i(TAG, "initTab: 1"+txt);
                tab1.setSelected(true);
                tab_current = tab1;
                tab1.setBackgroundResource(R.drawable.order_tab_active_border); //设置tab1当前背景
                myOrder_vp.setCurrentItem(0,true);
                break;
            case "待付款":
                tab2.setSelected(true);
                tab_current = tab2;
                tab2.setBackgroundResource(R.drawable.order_tab_active_border);
                myOrder_vp.setCurrentItem(1,true);
                break;
            case "待发货":
                tab3.setSelected(true);
                tab_current = tab3;
                tab3.setBackgroundResource(R.drawable.order_tab_active_border);
                myOrder_vp.setCurrentItem(2,true);
                break;
            case "待收货":
                tab4.setSelected(true);
                tab_current = tab4;
                tab4.setBackgroundResource(R.drawable.order_tab_active_border);
                myOrder_vp.setCurrentItem(3,true);
                break;
            case "已完成":
                tab5.setSelected(true);
                tab_current = tab5;
                tab5.setBackgroundResource(R.drawable.order_tab_active_border);
                myOrder_vp.setCurrentItem(4,true);
                break;
            default:
                tab1.setSelected(true);
                tab_current = tab1;
                tab1.setBackgroundResource(R.drawable.order_tab_active_border);
                myOrder_vp.setCurrentItem(0,true);
                break;
        }
        tab1.setOnClickListener(this);
        tab2.setOnClickListener(this);
        tab3.setOnClickListener(this);
        tab4.setOnClickListener(this);
        tab5.setOnClickListener(this);

    }


    /**
     * todo 初始化 ViewPager2
     */
    private void initPager() {
        list.add(MyOrderFragment.newInstance(99,1));
        list.add(MyOrderFragment.newInstance(1,1));
        list.add(MyOrderFragment.newInstance(2,1));
        list.add(MyOrderFragment.newInstance(3,1));
        list.add(MyOrderFragment.newInstance(98,1));
        MyOrderAdapter myOrderAdapter =  new MyOrderAdapter(getSupportFragmentManager(),getLifecycle(),list);
        myOrder_vp.setAdapter(myOrderAdapter);

        myOrder_vp.setOffscreenPageLimit(5); //预加载页面数

        //禁止左右滑动
        myOrder_vp.setUserInputEnabled(true);
        //滑动监听
        myOrder_vp.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                pageChange(position);
            }
        });
    }

    /**
     * todo 自定义方法,作为滑动监听事件
     * @param position
     */
    private void pageChange(int position) {
        tab_current.setSelected(false);
        switch (position){
            case R.id.tab1:
                clearBack();
                tab1.setBackgroundResource(R.drawable.order_tab_active_border);
                myOrder_vp.setCurrentItem(0,false);
                break;
            case 0:
                clearBack();
                tab1.setBackgroundResource(R.drawable.order_tab_active_border);
                tab1.setSelected(true);
                tab_current = tab1;
                break;
            case R.id.tab2:
                clearBack();
                tab2.setBackgroundResource(R.drawable.order_tab_active_border);
                myOrder_vp.setCurrentItem(1,false);
                break;
            case 1:
                clearBack();
                tab2.setBackgroundResource(R.drawable.order_tab_active_border);
                tab2.setSelected(true);
                tab_current = tab2;
                break;
            case R.id.tab3:
                clearBack();
                tab3.setBackgroundResource(R.drawable.order_tab_active_border);
                myOrder_vp.setCurrentItem(2,false);
                break;
            case 2:
                clearBack();
                tab3.setBackgroundResource(R.drawable.order_tab_active_border);
                tab3.setSelected(true);
                tab_current = tab3;
                break;
            case R.id.tab4:
                clearBack();
                tab4.setBackgroundResource(R.drawable.order_tab_active_border);
                myOrder_vp.setCurrentItem(3,false);
                break;
            case 3:
                clearBack();
                tab4.setBackgroundResource(R.drawable.order_tab_active_border);
                tab4.setSelected(true);
                tab_current = tab4;
                break;
            case R.id.tab5:
                clearBack();
                tab5.setBackgroundResource(R.drawable.order_tab_active_border);
                myOrder_vp.setCurrentItem(4,false);
                break;
            case 4:
                clearBack();
                tab5.setBackgroundResource(R.drawable.order_tab_active_border);
                tab5.setSelected(true);
                tab_current = tab5;
                break;
            case R.id.head_search:
                startActivity(new Intent(MyOrder.this, OrderSearch.class));
                break;
        }
    }

    /**
     * todo 清除背景
     */
    private void clearBack() {
       tab1.setBackgroundResource(R.drawable.order_tab_default_border);
       tab2.setBackgroundResource(R.drawable.order_tab_default_border);
       tab3.setBackgroundResource(R.drawable.order_tab_default_border);
       tab4.setBackgroundResource(R.drawable.order_tab_default_border);
       tab5.setBackgroundResource(R.drawable.order_tab_default_border);

    }

    @Override
    public void onClick(View v) {
        pageChange(v.getId());
    }
}

二. TabLayout + ViewPager2实现

TabLayout详细介绍可查看 TabLayou的简单用法

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".mime.order.my_order.MyOrder"
    android:orientation="vertical">
    <include layout="@layout/classify_head" />
    
    //tabLayout
    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tab_layout"
        android:background="@color/white"
        app:tabTextColor="@color/theme_defaultText"
        app:tabSelectedTextColor="@color/theme_color"
        app:tabIndicatorColor="@color/theme_color"
        app:tabIndicatorHeight="2dp"
        android:layout_width="match_parent"
        android:layout_height="40dp"/>
        
     //ViewPager2
    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/myOrder_vp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>
  private TabLayout tabLayout;
  private String[] tabTitle_list={"全部","待付款","待发货","待收货","已完成"};
   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_order);
        if(getIntent() !=null){
            order_code = getIntent().getIntExtra("order_code",0);
            txt = getIntent().getStringExtra("txt");
        }

        initView();
    }


    /**
     * todo initView 初始化控件
     */
    private void initView() {
        tabLayout = findViewById(R.id.tab_layout);
        myOrder_vp  = findViewById(R.id.myOrder_vp);
        head_search = findViewById(R.id.head_search);

        //wang添加 2021/7/13
        default_tv = findViewById(R.id.default_tv);
        default_tv.setText("搜索订单");
        default_tv.setVisibility(View.VISIBLE);

        head_search.setOnClickListener(this);

        initPager();
    }

    /**
     * todo 初始化 ViewPager2
     */
    private void initPager() {
        list.add(MyOrderFragment.newInstance(99,1));
        list.add(MyOrderFragment.newInstance(1,1));
        list.add(MyOrderFragment.newInstance(2,1));
        list.add(MyOrderFragment.newInstance(3,1));
        list.add(MyOrderFragment.newInstance(98,1));
        MyOrderAdapter myOrderAdapter =  new MyOrderAdapter(getSupportFragmentManager(),getLifecycle(),list);
        myOrder_vp.setAdapter(myOrderAdapter);

        myOrder_vp.setOffscreenPageLimit(5); //预加载页面数

        //禁止左右滑动,false为禁止
        myOrder_vp.setUserInputEnabled(true);

        //这里必须要在添加适配器完了之后才能新建该方法
        new TabLayoutMediator(tabLayout, myOrder_vp, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
             //就是将标题内容分别相对应的赋值
                tab.setText(tabTitle_list[position]);
            }
        }).attach();  //最后一定要.attach()
    }



  //适配器
 public class MyOrderAdapter extends FragmentStateAdapter {
    private List<Fragment> list = new ArrayList<>();

    public MyOrderAdapter(@NonNull FragmentManager fragmentManager, @NonNull Lifecycle lifecycle ,List<Fragment> list) {
        super(fragmentManager, lifecycle);
        this.list = list;
    }


    @NonNull
    @Override
    public Fragment createFragment(int position) {
        return list.get(position);
    }

    @Override
    public int getItemCount() {
        return list.size();
    }
}
``

以上是关于TabLayout+ViewPager2的联合使用的主要内容,如果未能解决你的问题,请参考以下文章

android使用Tablayout+viewpager2

由于 ViewPager2 导致 TabLayout 损坏

如何更新 Tablayout 中的片段? (Viewpager2, FragmentStateAdapter)

一起Talk Android吧(第三百七十七回:使用ViewPager2+TabLayout遇到的问题)

使用ViewPager2+TabLayout设计主布局

使用ViewPager2+TabLayout设计主布局