1. 前言
Google 在 androidx 组件包里增加了一个新的组件 ViewPager2,目前已经更新了两个 alpha 版本了。那么,和之前的 ViewPager 组件相比,有什么改进呢?查看官方文档,有下面一段话:
ViewPager2 replaces ViewPager, addressing most of its predecessor’s pain-points, including right-to-left layout support, vertical orientation, modifiable Fragment collections, etc.
ViewPager2 用来替换 ViewPager,解决 ViewPager 的多数痛点,包括 RTL 布局支持,垂直方向滚动,可修改的 Fragment 集合等等。
再查看一下 ViewPager2 的 Release Notes,可以看到:
-
Version 1.0.0-alpha02
新特性:能够关闭用户输入(setUserInputEnabled, isUserInputEnabled)
API 变更:ViewPager2 声明为 final 类 -
Version 1.0.0-alpha01
新特性:支持 RTL 布局,支持竖直方向滚动,功能齐全的 notifyDataSetChanged
API 变更:FragmentStateAdapter 替代 FragmentStatePagerAdapter;RecyclerView.Adapter 替代 PagerAdapter;registerOnPageChangeCallback 替代 addPageChangeListener。好了,初步了解了 ViewPager2,下边开始代码演示。
2. 正文
引入 ViewPager2 组件:
dependencies {
implementation "androidx.viewpager2:viewpager2:1.0.0-alpha02"
}
2.1 水平滚动
把 ViewPager2 声明在 activity_horizontal_scrolling.xml 里面:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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=".MainActivity">
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/viewpager2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_width="0dp"
android:layout_height="0dp"/>
</androidx.constraintlayout.widget.ConstraintLayout>
建立一个简单的 item 布局,item_page.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="@+id/container"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.appcompat.widget.AppCompatTextView
android:id="@+id/tvTitle"
tools:text="item"
android:layout_centerInParent="true"
android:textColor="@android:color/white"
android:textSize="32dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
建立数据适配器 ViewPagerAdapter:
public class ViewPagerAdapter extends RecyclerView.Adapter<ViewPagerAdapter.ViewPagerViewHolder> {
private List<Integer> colors = new ArrayList<>();
{
colors.add(android.R.color.black);
colors.add(android.R.color.holo_purple);
colors.add(android.R.color

本文详细介绍了AndroidX的新组件ViewPager2,对比了它与ViewPager的改进,如支持RTL布局、垂直滚动和可修改的Fragment集合。通过实例展示了ViewPager2的水平和垂直滚动,以及如何使用FragmentStateAdapter实现TabLayout与ViewPager2的结合。还演示了notifyDataSetChanged方法的使用。文章提醒读者ViewPager2仍处于alpha阶段,可能存在问题。
最低0.47元/天 解锁文章
1722

被折叠的 条评论
为什么被折叠?



