大家都知道Google最近发布的ViewPager2基本不兼容ViewPager,虽然众多特性仍然可以使用,但两者在代码和应用方面相差甚远。就比如ViewPager的显示左右ITEM使用在ViewPager2之上仍然会留下左右的边距,但是静止状态下无法显示出左右item,滑动状态下却可以显示出来,解决这一个问题的关键仍然需要clipChildren,只是要在item布局嵌套一层外部布局
先介绍clipChildren属性
clipChildren是将子view的大小范围控制在父布局以内,默认值为true。假设我们将其设置为false,将子布局大小设置超过父布局,实际的展示上子view将显示的比父布局更大
以往ViewPager显示左右ITEM
设置Layout的ViewPager左右margin并且在viewPager及其父布局加入android:clipChildren="false"就可以完美实现显示左右ITEM
ViewPager2如何实现左右显示ITEM呢
第一步的步骤大体相同,也是在ViewPager2的Layout层加入margin以及clipChildren,但是设置这个属性后有些低版本系统仍然不支持怎么办呢?我们需要在ViewPager2的父布局加入android:layerType="software"防止布局开启硬件加速导致无法显示左右两侧的item
<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:id="@+id/viewPagerParentLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:layerType="software"
android:clipChildren="false"
tools:context=".MainActivity">
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/viewPager2"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_marginStart="50dp"
android:layout_marginEnd="50dp"
android:clipChildren="false"
/>
</LinearLayout>
第二步,对左右item有边距要求的话,对item的Layout层进行一定的修改,在顶层布局中加入左右margin
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp"
android:background="@android:color/darker_gray"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center_horizontal"
android:text="欢迎加入作者的公众号:\n松果果科技星球"
android:textAlignment="center"
android:textSize="20sp" />
<ImageView
android:id="@+id/ivImg"
android:layout_width="200dp"
android:layout_height="200dp"
android:scaleType="fitCenter" />
</LinearLayout>
第三步,在activity层动态设置ViewPager2的属性
viewPager2.offscreenPageLimit = 3
如果需要动态关闭布局加速,在activity设置viewPager2父布局的layerType
viewPagerParentLayout.setLayerType(View.LAYER_TYPE_SOFTWARE,null);