安卓开发中的ViewPager2的使用

一、ViewPager2介绍

ViewPager2 Android Jetpack 中的一个组件,它是 ViewPager 的改进版本,提供了更好的性能和更多的功能。ViewPager2 支持水平和垂直滑动,以及与 RecyclerView 类似的数据加载和视图回收机制。

以下是 ViewPager2 的一些主要作用和特点:

  1. 页面浏览:允许用户通过滑动手势在不同的页面之间切换,适用于浏览图片、文章、设置选项等。

  2. 动态内容加载ViewPager2 可以与 Fragment 结合使用,实现动态内容的加载和卸载,提高应用的性能和内存使用效率。

  3. 视图回收机制:当用户滑动时,不可见的页面会被回收,而新的页面会被创建,这样可以有效地管理内存和资源。

  4. 灵活的布局:支持水平和垂直滑动,可以根据应用的需求选择不同的布局方向。

  5. 页面指示器:可以与 TabLaout 或其他页面指示器组件结合使用,提供用户当前浏览页面的直观反馈。

  6. 页面变换效果:支持自定义页面变换效果,如缩放、滑动、淡入淡出等,增强用户体验。

  7. 懒加载:可以实现懒加载机制,即只有当页面即将显示在屏幕上时,才加载页面内容,从而提高应用的响应速度和性能。

  8. 无限循环滑动:可以设置 ViewPager2 为无限循环滑动,适用于轮播图等场景。

  9. 与动画和过渡效果集成:可以与 Android 的动画和过渡效果集成,提供平滑的页面切换体验。

  10. 状态恢复:在配置更改(如屏幕旋转)后,ViewPager2 可以保存和恢复页面状态,确保用户体验的连贯性。

  11. 与现代架构组件集成ViewPager2 可以与 Android Jetpack 的其他组件(如 ViewModel、LiveData 等)集成,构建现代化的 Android 应用。

  12. 更好的生命周期管理:与 ViewPager 相比,ViewPager2 提供了更好的 Fragment 生命周期管理,确保 Fragment 在适当的时机进行创建、销毁和重建。


二、ViewPager2的使用

1、定义fragment文件

项目内容需要的一些布局文件,可以忽视,学习ViewPager2的时候没必要写这么麻烦

<?xml version="1.0" encoding="utf-8"?>
<layout 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">

    <data>

    </data>

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/base_gray_f7">

            <androidx.appcompat.widget.AppCompatTextView
                android:id="@+id/print_dialog_swing_fun_edit_mode_tv"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/print_dialog_swing_fun_edit_mode_tv"
                android:textColor="@color/black"
                android:textStyle="bold"
                android:textSize="@dimen/dp_11"
                android:layout_marginTop="@dimen/dp_9"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintTop_toTopOf="parent"/>

            <androidx.constraintlayout.widget.ConstraintLayout
                android:id="@+id/EditImageConstraintLayout"
                android:layout_width="match_parent"
                android:layout_height="@dimen/dp_429"
                android:layout_marginHorizontal="@dimen/dp_29"
                android:layout_marginTop="@dimen/dp_9"
                android:background="@drawable/print_swing_fun_edit_dashed_iv_border"
                app:layout_constraintTop_toBottomOf="@+id/print_dialog_swing_fun_edit_mode_tv"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintEnd_toEndOf="parent">

                <androidx.appcompat.widget.AppCompatImageView
                    android:id="@+id/face_photo"
                    android:layout_width="0dp"
                    android:layout_height="0dp"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintTop_toTopOf="parent"
                    app:layout_constraintBottom_toBottomOf="parent"/>

                <androidx.appcompat.widget.AppCompatImageView
                    android:id="@+id/mode_photo"
                    android:layout_width="0dp"
                    android:layout_height="0dp"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintTop_toTopOf="parent"
                    app:layout_constraintBottom_toBottomOf="parent"/>

                <androidx.appcompat.widget.AppCompatImageView
                    android:id="@+id/paster_photo"
                    android:layout_width="0dp"
                    android:layout_height="0dp"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintTop_toTopOf="parent"
                    app:layout_constraintBottom_toBottomOf="parent"/>

            </androidx.constraintlayout.widget.ConstraintLayout>

            <com.mango.beauty.textview.CornersTextView
                android:id="@+id/index_num_tv"
                android:layout_width="@dimen/dp_65"
                android:layout_height="@dimen/dp_25"
                android:text="1/3"
                android:textSize="@dimen/dp_12"
                android:textStyle="bold"
                android:gravity="center"
                app:ctv_radius="@dimen/dp_14"
                app:ctv_solidColor="@color/white"
                android:layout_marginTop="@dimen/dp_10"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/EditImageConstraintLayout"/>




            <androidx.appcompat.widget.LinearLayoutCompat
                android:id="@+id/print_act_swing_fun_photo_edit_group"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:paddingTop="@dimen/dp_11"
                android:background="@color/white"
                android:paddingBottom="@dimen/dp_18"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintBottom_toBottomOf="parent">

                <androidx.appcompat.widget.LinearLayoutCompat
                    android:id="@+id/print_act_swing_fun_photo_edit_ll"
                    android:layout_width="@dimen/dp_38"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="@dimen/dp_13"
                    android:orientation="vertical"
                    android:layout_marginTop="5dp"
                    app:layout_constraintBottom_toBottomOf="@+id/print_act_swing_fun_photo_list_next"
                    app:layout_constraintEnd_toStartOf="@+id/print_act_swing_fun_photo_list_next"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toTopOf="@+id/print_act_swing_fun_photo_list_next">

                    <androidx.appcompat.widget.AppCompatImageView
                        android:id="@+id/print_act_swing_fun_photo_edit_delete_iv"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center"
                        android:layout_marginBottom="@dimen/dp_3"
                        android:src="@mipmap/print_png_swing_fun_edit_delete" />

                    <androidx.appcompat.widget.AppCompatTextView
                        android:id="@+id/print_act_swing_fun_photo_edit_change"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:maxLines="1"
                        android:layout_gravity="center"
                        android:textStyle="bold"
                        android:text="@string/print_dialog_swing_fun_edit_delete"
                        android:textColor="@color/base_dark_36"
                        android:textSize="@dimen/dp_12"/>

                </androidx.appcompat.widget.LinearLayoutCompat>

                <com.mango.beauty.textview.CornersTextView
                    android:id="@+id/print_act_swing_fun_photo_edit_next"
                    android:layout_width="wrap_content"
                    android:layout_height="@dimen/dp_42"
                    android:layout_marginStart="@dimen/dp_14"
                    android:layout_marginEnd="@dimen/dp_11"
                    android:paddingHorizontal="@dimen/dp_106"
                    android:gravity="center"
                    android:text="@string/print_photo_setting_dialog_bind_setting_submit"
                    android:textColor="@color/base_white"
                    android:textSize="@dimen/dp_17"
                    app:ctv_radius="@dimen/dp_6"
                    app:ctv_solidColor="@color/bd_blue_217"/>
            </androidx.appcompat.widget.LinearLayoutCompat>


        </androidx.constraintlayout.widget.ConstraintLayout>

</layout>

2、定义ViewPager2使用的页面

<?xml version="1.0" encoding="utf-8"?>
<layout 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">

    <data>
        <import type="android.view.View" />
    </data>


    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/base_gray_f7">

        <include
            android:id="@+id/print_act_title"
            layout="@layout/base_include_title" />

        <androidx.viewpager2.widget.ViewPager2
            android:id="@+id/vp_photo_edit"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:orientation="horizontal"
            android:scrollbars="none"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/print_act_title"/>

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

 3、定义fragment页面

就是初始化一些页面内容(封装之后的),然后增加了一个静态方法getFragment用于创建 SwingFunEditFrag 的实例,并且可以通过方法参数传递数据到 Fragment。这些数据被打包到一个 Bundle 中,并通过 setArguments 方法传递给 Fragment。

class SwingFunEditFrag : BaseFragmentX<PrintFragSwingFunEditBinding>() {

    companion object{
        fun getFragment(
            total:Int= 0,
            position:Int,
            headPhotos: String
        ):SwingFunEditFrag{
            val frag = SwingFunEditFrag()
            val bundle = Bundle()
            bundle.putInt(Key2Config.TOTAL,total)
            bundle.putInt(Key2Config.POSITION,position)
            bundle.putString(Key2Config.HEAD_PHOTOS,headPhotos)
            frag.arguments = bundle
            return frag
        }
    }

    override fun setLayoutId(): Int = R.layout.print_frag_swing_fun_edit

    override fun onLazyLoad() {
        val total = arguments?.getInt(Key2Config.TOTAL)?:0
        val position = arguments?.getInt(Key2Config.POSITION)?:0
        val headPhotos = arguments?.getString(Key2Config.HEAD_PHOTOS)?:0
        mDatabind.indexNumTv.text = "${position+1}/$total"
        
        ......
    }
}

4、定义ViewPager2的适配器

在ViewPagerAdapter的构造函数中也可以传一些自己需要的一些数据,感觉自己把这些东西学死了,不会灵活变通啊

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Lifecycle
import androidx.viewpager2.adapter.FragmentStateAdapter

class ViewPagerAdapter(
    fragmentManager: FragmentManager,
    lifecycle: Lifecycle,
    private val selectedPhotos: ArrayList<String>
) : FragmentStateAdapter(fragmentManager, lifecycle) {

    private val mFrags = mutableListOf<Fragment>().apply {
        for (i in 0 until selectedPhotos.size) {
            add(SwingFunEditFrag.getFragment(selectedPhotos.size, i, selectedPhotos[i]))
        }
    }

    override fun getItemCount(): Int = selectedPhotos.size

    override fun createFragment(position: Int): Fragment {
        // 根据位置返回不同的Fragment
        return mFrags[position]
    }

    override fun getItemId(position: Int): Long {
        return super.getItemId(position)
    }
}

然后解释下下面这段代码的作用:

    private val mFrags = mutableListOf<Fragment>().apply {
        for (i in 0 until selectedPhotos.size) {
            add(SwingFunEditFrag.getFragment(selectedPhotos.size, i, selectedPhotos[i]))
        }
    }
  • 创建 MutableList: mutableListOf<Fragment>() 创建了一个可变的 Fragment 列表
  • 使用 apply 函数: .apply 是 Kotlin 中的一个扩展函数,它允许在创建对象的同时执行一些初始化操作。这里的 apply 函数接收一个 lambda 表达式,该表达式包含了对 mFrags 列表的操作。
  • 循环遍历 selectedPhotos 列表: for (i in 0 until selectedPhotos.size) 循环遍历 selectedPhotos 列表的索引,从 0 开始直到 selectedPhotos.size(不包括 selectedPhotos.size)。
  • 创建 Fragment 实例: 在循环体内,调用 SwingFunEditFrag.getFragment 静态工厂方法来创建 SwingFunEditFrag 的实例
  • 将 Fragment 添加到 mFrags 列表: add(SwingFunEditFrag.getFragment(...)) 将创建的 Fragment 实例添加到 mFrags 列表中。

简单来说,最终mFrags 列表将包含与 selectedPhotos 列表中每个数据项对应的 Fragment 实例。当 ViewPager2 需要创建页面时,它将使用适配器中的 createFragment 方法,该方法返回 mFrags 列表中相应位置的 Fragment 实例。

这种方式允许 ViewPager2 通过适配器模式与 Fragment 分离,使得 ViewPager2 可以动态地管理和展示多个 Fragment 页面。

补充:SwingFunEditFrag.getFragment 这个方法接收以下参数:

  1. selectedPhotos.size:selectedPhotos 列表的总大小,可能用于传递给 Fragment 表示总页面数。
  2. i:当前循环的索引,表示 Fragment 在 ViewPager2 中的位置。
  3. selectedPhotos[i]:selectedPhotos 列表中当前索引处的字符串,它可能代表一个图片 URL 或其他与页面内容相关的数据。

5、在Activity中配置ViewPager

这个适配器配置方法和RecycleView的适配器方法是一样的,使用如下:

        val adapter = ViewPagerAdapter(supportFragmentManager,lifecycle,selectedPhotos)
        mDataBind.vpPhotoEdit.adapter = adapter

        

三、总结

        在这个位置卡了2天啊,因为传参的问题,因为项目中有个需求是需要把这个selectedPhotos数组经过网络请求处理一下,生成一个新的列表,在这里的Activity我就想直接发起网络请求把处理过的列表传过去,结果因为网络请求是耗时操作,在实例化这个ViewPager适配器的时候,网络请求还没有处理完成,所以传递过去的列表一直为空,导致在适配器中配置页面时数量一直为0,所以定义的fragment页面一直无法正常显示,找了两天才找到问题!!!之前一直觉得是我页面其它地方写的有问题,没考虑到是传参的问题,我还寻思这个ViewPager2怎么这么难用啊,原因是自己蠢不怪ViewPager2

  • 8
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值