Android ViewPager2 Right to Left (RTL) Scroll (Reverse Scroll Direction)

July 5, 2019
ViewCompat.setLayoutDirection(viewPager, ViewCompat.LAYOUT_DIRECTION_RTL)

NOTE: Only supported on API 17 and above

via xml

<androidx.viewpager2.widget.ViewPager2
        android:layoutDirection="rtl"
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

Edit AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
    <application
            ...
            android:supportsRtl="true">

    </application>
</manifest>

layoutDirection will cascade to all child views.

My purpose is not to implement RTL text display (I just wanted RTL scrolling), so I want want to reset layoutDirection in the child layout via android:layoutDirection="locale".

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        app:cardUseCompatPadding="true"
        app:cardCornerRadius="12dp"
        android:layout_margin="8dp"
        android:layoutDirection="locale">

    <LinearLayout android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:layout_gravity="center"
                  android:orientation="vertical"
                  android:padding="8dp">

        <TextView
                android:id="@+id/titleTextView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAppearance="@style/TextAppearance.AppCompat.Large"
                android:textAlignment="center"
                tools:text="Title"
        />

    </LinearLayout>
</androidx.cardview.widget.CardView>
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.