关于TabLayout+ViewPager2的使用以及相关问题点

1.前言

  • 最新项目需要用到TabLayout+ViewPager实现对应的功能,后来发现ViewPager的实现方法被废弃掉了(虽然还可以用,但有坑后面说),Google推荐用新一点的ViewPager2来代替,下面来谈谈我用到的。

2.特点

  • 实现标题栏和内容联动切换
  • 用多个TabLayout关联多个fragment页面

3.代码及说明

3.1.先上效果图

在这里插入图片描述

3.2.代码如下

3.2.1.首先在app的build.gradle文件下加入依赖

implementation 'androidx.viewpager2:viewpager2:1.0.0'
implementation "com.google.android.material:material:1.1.0"

3.2.2.activity的布局如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

	//这里省略了toolbar
   ...

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabBackground="@color/transparency_color"
        app:tabIndicator="@color/text_FB6137"
        app:tabIndicatorColor="@color/text_FB6137"
        app:tabMode="scrollable"
        app:tabRippleColor="@color/transparency_color"
        app:tabSelectedTextColor="#333333"
        app:tabTextColor="@color/text_normal_color">

    </com.google.android.material.tabs.TabLayout>

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="@dimen/margin_10" />

</LinearLayout>

3.2.3.activity类的主要代码如下

private String[] mTitles = {"关注","收藏","点赞👍"};


@Override
public void initData() {
    for (int i = 0; i < mTitles.length; i++) {
        mTabLayout.addTab(mTabLayout.newTab().setText(mTitles[i]), false);
    }
    mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            TextView textView = new TextView(getActivity());
            float selectedSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, 20, getResources().getDisplayMetrics());
            textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, selectedSize);
            textView.setTextColor(getResources().getColor(R.color.text_222222));
            textView.setText(tab.getText());
            textView.setGravity(Gravity.CENTER_HORIZONTAL);
            textView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
            tab.setCustomView(textView);
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
            tab.setCustomView(null);
        }

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

        }
    });
    //禁用预加载
    mViewPager2.setOffscreenPageLimit(ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT);
    mViewPager2.setAdapter(new FragmentStateAdapter(getSupportFragmentManager(),getLifecycle()) {
        @NonNull
        @Override
        public Fragment createFragment(int position) {
            return PagerFragment.newInstance(position);
        }

        @Override
        public int getItemCount() {
            return mTitles.length;
        }
    });

    new TabLayoutMediator(mTabLayout, mViewPager2, new TabLayoutMediator.TabConfigurationStrategy() {
        @Override
        public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
            tab.setText(mTitles[position]);
        }
    }).attach();

    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(10);
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mTabLayout.getTabAt(1).select();//默认选中第二个
                        mViewPager2.setCurrentItem(1);
                    }
                });
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }).start();
}    

3.2.4.fragment的布局如下:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/iv"
        tools:background="@mipmap/ic_page1"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</androidx.constraintlayout.widget.ConstraintLayout>

3.2.5.fragment类的代码如下:

public class PagerFragment extends BaseFragment {
    private static final String KEY_POSITION = "position";

    @BindView(R.id.iv)
    ImageView mIv;

    public static PagerFragment newInstance(int position) {
        PagerFragment fragment = new PagerFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(KEY_POSITION, position);
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    public int setContentLayout() {
        return R.layout.fragment_pager;
    }

    @Override
    public void initToolBar() {

    }

    @Override
    public void initPresenter() {

    }

    @Override
    public void initData() {
        int position = getArguments().getInt(KEY_POSITION);
        if (position == 0) {
            mIv.setImageResource(R.mipmap.ic_page1);
        } else if (position == 1) {
            mIv.setImageResource(R.mipmap.ic_page2);
        } else {
            mIv.setImageResource(R.mipmap.ic_page3);
        }
    }

    @Override
    public void onDestroyFragment() {

    }
}

到这里功能就结束了!

4.问题点

4.1.导入依赖冲突
  • 在项目里有用到Google原生的下拉刷新库swiperefreshlayout,通过重新添加依赖解决的
4.2.默认选中问题

一开始进入页面设置默认选中第二个title

//单纯的设置下面这行代码,并没有用
mViewPager2.setCurrentItem(1);

需要这么做才行

new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(10);
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mTabLayout.getTabAt(1).select();//默认选中第二个
                            mViewPager2.setCurrentItem(1);
                        }
                    });
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
4.3.源码

附上源码地址:github源码(平时的demo)

5.最后

开通了个公众号,扫码关注一下,可以获得超过1个G的免费PDF书籍学习资料,并且可以及时收到我分享的内容哦!
在这里插入图片描述

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值