Android ViewPager、ViewPager2的基本使用详解及区别

本文详细介绍了Android中的ViewPager和ViewPager2的使用方法,包括它们各自与TabLayout的结合,以及它们的区别。在布局上,ViewPager允许有子View,而ViewPager2则不允许。在Adapter继承上,ViewPager使用FragmentStatePagerAdapter,而ViewPager2使用FragmentStateAdapter。在设置Fragment和关联TabLayout的方式上,两者也有不同。
摘要由CSDN通过智能技术生成

本篇Blog记录ViewPager和ViewPager2

嵌套Fragment的效果图

嵌套Fragment效果

ViewPager的使用

关于ViewPager的使用已经很常见了,这里在复习一下吧。配合TabLayout

  1. 布局文件

    在ViewPager的布局中允许存在子view,我们可以把TabLayout作为ViewPager的子View写在ViewPager内部,也可以并列。

		<androidx.viewpager.widget.ViewPager
            android:id="@+id/vp_merchant_main"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            app:layout_constraintVertical_weight="1"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toBottomOf="@id/banner_merchant_main"
            app:layout_constraintBottom_toBottomOf="parent">

            <com.google.android.material.tabs.TabLayout
                android:id="@+id/tab_layout_merchant_main"
                android:layout_width="match_parent"
                android:layout_height="50dp"
                app:tabGravity="center"
                app:tabIndicatorColor="@color/tabLayoutIndicatorStartColor"
                app:tabSelectedTextColor="@color/textColor"
                app:tabTextAppearance="@android:style/TextAppearance.Holo"
                app:tabTextColor="@color/defaultTextColor" />
        </androidx.viewpager.widget.ViewPager>
  1. Java代码

    代码中我们只需要把Fragment和Titles传入Adapter,然后再设置到ViewPager上就可以了。

    我们也可以调用Tablayout的setupWithViewPager()方法使TabLayout和ViewPager进行绑定

		// ViewPager处理
        ArrayList<Fragment> fragmentList = new ArrayList<>();
        fragmentList.add(new AllProductFragment(this));
        fragmentList.add(new EvaluationFragment(this));
        String[] fragmentTitles = {
   "商品", "评价"};
        ViewPagerScrollAdapter scrollAdapter = new ViewPagerScrollAdapter(getSupportFragmentManager());
        scrollAdapter.
  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值