ViewPager2在RTL模式下默认位置不是position 0的问题

978 阅读1分钟

代码如下:

<androidx.constraintlayout.widget.ConstraintLayout
    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:clipChildren="false">

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginStart="99dp"
        android:layout_marginEnd="99dp"
        android:layoutDirection="rtl"
        app:layout_constraintDimensionRatio="178:227"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>

此时默认ViewPager2指向的位置是position 1而不是0;

若将ViewPager2改成RecyclerView,也有类似的问题.

去掉marginStart && marginEnd或者将layout_width改成0dp便不会出现此问题了,目前看是因为设置成match_parent之后RecyclerView自身测量出其自身宽度发生变化导致的,在1080P手机上,第一次测量出来的宽度是1080,其内部也是按照1080进行布局显示的,而第二次测量出来便是1080-99 * 2 * 3=486, 其内部用的是486计算的;

而0dp则自身宽度不会发生变化,始终是486