diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..aa724b7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,15 @@ +*.iml +.gradle +/local.properties +/.idea/caches +/.idea/libraries +/.idea/modules.xml +/.idea/workspace.xml +/.idea/navEditor.xml +/.idea/assetWizardSettings.xml +.DS_Store +/build +/captures +.externalNativeBuild +.cxx +local.properties diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/.idea/compiler.xml b/.idea/compiler.xml new file mode 100644 index 0000000..fb7f4a8 --- /dev/null +++ b/.idea/compiler.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/gradle.xml b/.idea/gradle.xml new file mode 100644 index 0000000..d61a12a --- /dev/null +++ b/.idea/gradle.xml @@ -0,0 +1,21 @@ + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..e92eb2d --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..c0da1bf --- /dev/null +++ b/README.md @@ -0,0 +1,37 @@ +# ViewPager2ForSupport + +As we know, there still are so many legacy projects using support library so far. ViewPager2 contains +many useful features, which is better than ViewPager. However, unfortunately, it is exclusively +for androidx, and support can't use it. In order to use it on legacy support project, I migrate +androidx.viewpager2:viewpager2:1.0.0 to support version. So you can use it in your support project. + +### Usage: + +#### Step 1. Add the JitPack repository to your build file + +Add it in your root build.gradle at the end of repositories: +```groovy + allprojects { + repositories { + ... + maven { url 'https://jitpack.io' } + } + } +``` + +#### Step 2. Add the dependency + +```groovy + dependencies { + implementation 'com.github.VinsonGuo:ViewPager2ForSupport:1.0.0' + } +``` + +#### Step 3. Use it + +```xml + +``` \ No newline at end of file diff --git a/app/.gitignore b/app/.gitignore new file mode 100644 index 0000000..42afabf --- /dev/null +++ b/app/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/app/build.gradle b/app/build.gradle new file mode 100644 index 0000000..3e1335c --- /dev/null +++ b/app/build.gradle @@ -0,0 +1,42 @@ +plugins { + id 'com.android.application' + id 'kotlin-android' +} + +android { + compileSdk 31 + + defaultConfig { + applicationId "com.vinsonguo.viewpager2" + minSdk 23 + targetSdk 31 + versionCode 1 + versionName "1.0" + + testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + kotlinOptions { + jvmTarget = '1.8' + } +} + +dependencies { + + implementation 'com.android.support:appcompat-v7:28.0.0' + implementation 'com.android.support.constraint:constraint-layout:2.0.4' + implementation project(path: ':viewpager2') + testImplementation 'junit:junit:4.+' + androidTestImplementation 'com.android.support.test:runner:1.0.2' + androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' +} \ No newline at end of file diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100644 index 0000000..481bb43 --- /dev/null +++ b/app/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile \ No newline at end of file diff --git a/app/src/androidTest/java/com/vinsonguo/viewpager2/ExampleInstrumentedTest.kt b/app/src/androidTest/java/com/vinsonguo/viewpager2/ExampleInstrumentedTest.kt new file mode 100644 index 0000000..e5a8ded --- /dev/null +++ b/app/src/androidTest/java/com/vinsonguo/viewpager2/ExampleInstrumentedTest.kt @@ -0,0 +1,24 @@ +package com.vinsonguo.viewpager2 + +import android.support.test.InstrumentationRegistry +import android.support.test.runner.AndroidJUnit4 + +import org.junit.Test +import org.junit.runner.RunWith + +import org.junit.Assert.* + +/** + * Instrumented test, which will execute on an Android device. + * + * See [testing documentation](http://d.android.com/tools/testing). + */ +@RunWith(AndroidJUnit4::class) +class ExampleInstrumentedTest { + @Test + fun useAppContext() { + // Context of the app under test. + val appContext = InstrumentationRegistry.getInstrumentation().targetContext + assertEquals("com.vinsonguo.viewpager2", appContext.packageName) + } +} \ No newline at end of file diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..82cc42b --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/java/com/vinsonguo/viewpager2/demo/MainActivity.kt b/app/src/main/java/com/vinsonguo/viewpager2/demo/MainActivity.kt new file mode 100644 index 0000000..bc3c5ed --- /dev/null +++ b/app/src/main/java/com/vinsonguo/viewpager2/demo/MainActivity.kt @@ -0,0 +1,24 @@ +package com.vinsonguo.viewpager2.demo + +import android.support.v7.app.AppCompatActivity +import android.os.Bundle +import android.support.v4.app.Fragment +import com.vinsonguo.viewpager2.R +import com.vinsonguo.viewpager2.adapter.FragmentStateAdapter +import com.vinsonguo.viewpager2.widget.ViewPager2 + +class MainActivity : AppCompatActivity() { + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_main) + + val viewPager2 = findViewById(R.id.viewPager2) +// viewPager2.isUserInputEnabled = false +// viewPager2.offscreenPageLimit = 3 + viewPager2.adapter = object :FragmentStateAdapter(this) { + override fun getItemCount() = 10 + override fun createFragment(position: Int) = TestFragment.newInstance(position) + + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/vinsonguo/viewpager2/demo/TestFragment.kt b/app/src/main/java/com/vinsonguo/viewpager2/demo/TestFragment.kt new file mode 100644 index 0000000..c31e9cd --- /dev/null +++ b/app/src/main/java/com/vinsonguo/viewpager2/demo/TestFragment.kt @@ -0,0 +1,79 @@ +package com.vinsonguo.viewpager2.demo + +import android.os.Bundle +import android.support.v4.app.Fragment +import android.util.Log +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.TextView + +class TestFragment:Fragment() { + + companion object{ + fun newInstance(index: Int) = TestFragment().apply { + val args = Bundle() + args.putInt("index", index) + arguments = args + } + } + + private val TAG by lazy { + "TestFragment" + arguments?.getInt("index") + } + + private lateinit var tv:TextView + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + Log.d(TAG, "onCreate \n") + } + + override fun onCreateView( + inflater: LayoutInflater, + container: ViewGroup?, + savedInstanceState: Bundle? + ): View? { + tv = TextView(context) + tv.append("onCreateView \n") + Log.d(TAG, "onCreateView \n") + return tv + } + + override fun onStart() { + super.onStart() + tv.append("onStart \n") + Log.d(TAG, "onStart \n") + } + + override fun onResume() { + super.onResume() + tv.append("onResume \n") + Log.d(TAG, "onResume \n") + } + + override fun onPause() { + super.onPause() + tv.append("onPause \n") + Log.d(TAG, "onPause \n") + } + + override fun onStop() { + super.onStop() + tv.append("onStop \n") + Log.d(TAG, "onStop \n") + } + + override fun onDestroyView() { + super.onDestroyView() + tv.append("onDestroyView \n") + Log.d(TAG, "onDestroyView \n") + } + + override fun onDestroy() { + super.onDestroy() + tv.append("onDestroy \n") + Log.d(TAG, "onDestroy \n") + } +} \ No newline at end of file diff --git a/app/src/main/res/drawable-v24/ic_launcher_foreground.xml b/app/src/main/res/drawable-v24/ic_launcher_foreground.xml new file mode 100644 index 0000000..9a32d34 --- /dev/null +++ b/app/src/main/res/drawable-v24/ic_launcher_foreground.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/ic_launcher_background.xml b/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..6209112 --- /dev/null +++ b/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,137 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml new file mode 100644 index 0000000..3495a48 --- /dev/null +++ b/app/src/main/res/layout/activity_main.xml @@ -0,0 +1,16 @@ + + + + \ No newline at end of file diff --git a/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..eca70cf --- /dev/null +++ b/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 0000000..eca70cf --- /dev/null +++ b/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher.webp b/app/src/main/res/mipmap-hdpi/ic_launcher.webp new file mode 100644 index 0000000..c209e78 Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp new file mode 100644 index 0000000..b2dfe3d Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher.webp b/app/src/main/res/mipmap-mdpi/ic_launcher.webp new file mode 100644 index 0000000..4f0f1d6 Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp new file mode 100644 index 0000000..62b611d Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher.webp b/app/src/main/res/mipmap-xhdpi/ic_launcher.webp new file mode 100644 index 0000000..948a307 Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp new file mode 100644 index 0000000..1b9a695 Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp b/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp new file mode 100644 index 0000000..28d4b77 Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp new file mode 100644 index 0000000..9287f50 Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp new file mode 100644 index 0000000..aa7d642 Binary files /dev/null and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp new file mode 100644 index 0000000..9126ae3 Binary files /dev/null and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/values-night/themes.xml b/app/src/main/res/values-night/themes.xml new file mode 100644 index 0000000..d06902d --- /dev/null +++ b/app/src/main/res/values-night/themes.xml @@ -0,0 +1,10 @@ + + + + \ No newline at end of file diff --git a/app/src/main/res/values/colors.xml b/app/src/main/res/values/colors.xml new file mode 100644 index 0000000..f8c6127 --- /dev/null +++ b/app/src/main/res/values/colors.xml @@ -0,0 +1,10 @@ + + + #FFBB86FC + #FF6200EE + #FF3700B3 + #FF03DAC5 + #FF018786 + #FF000000 + #FFFFFFFF + \ No newline at end of file diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..c74b5b2 --- /dev/null +++ b/app/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ + + ViewPager2ForSupport + \ No newline at end of file diff --git a/app/src/main/res/values/themes.xml b/app/src/main/res/values/themes.xml new file mode 100644 index 0000000..1a9fd80 --- /dev/null +++ b/app/src/main/res/values/themes.xml @@ -0,0 +1,10 @@ + + + + \ No newline at end of file diff --git a/app/src/test/java/com/vinsonguo/viewpager2/ExampleUnitTest.kt b/app/src/test/java/com/vinsonguo/viewpager2/ExampleUnitTest.kt new file mode 100644 index 0000000..bebbf63 --- /dev/null +++ b/app/src/test/java/com/vinsonguo/viewpager2/ExampleUnitTest.kt @@ -0,0 +1,17 @@ +package com.vinsonguo.viewpager2 + +import org.junit.Test + +import org.junit.Assert.* + +/** + * Example local unit test, which will execute on the development machine (host). + * + * See [testing documentation](http://d.android.com/tools/testing). + */ +class ExampleUnitTest { + @Test + fun addition_isCorrect() { + assertEquals(4, 2 + 2) + } +} \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..9db2bf1 --- /dev/null +++ b/build.gradle @@ -0,0 +1,18 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. +buildscript { + repositories { + google() + mavenCentral() + } + dependencies { + classpath "com.android.tools.build:gradle:7.0.2" + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.31" + + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files + } +} + +task clean(type: Delete) { + delete rootProject.buildDir +} \ No newline at end of file diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..7c98564 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,15 @@ +# Project-wide Gradle settings. +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +# org.gradle.parallel=true +# Kotlin code style for this project: "official" or "obsolete": +kotlin.code.style=official \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..e708b1c Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..26445d4 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Wed Feb 16 17:58:15 CST 2022 +distributionBase=GRADLE_USER_HOME +distributionUrl=https\://services.gradle.org/distributions/gradle-7.0.2-bin.zip +distributionPath=wrapper/dists +zipStorePath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..4f906e0 --- /dev/null +++ b/gradlew @@ -0,0 +1,185 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..107acd3 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..379cf1b --- /dev/null +++ b/settings.gradle @@ -0,0 +1,11 @@ +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + jcenter() // Warning: this repository is going to shut down soon + } +} +rootProject.name = "ViewPager2ForSupport" +include ':app' +include ':viewpager2' diff --git a/viewpager2/.gitignore b/viewpager2/.gitignore new file mode 100644 index 0000000..42afabf --- /dev/null +++ b/viewpager2/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/viewpager2/build.gradle b/viewpager2/build.gradle new file mode 100644 index 0000000..da4a4c5 --- /dev/null +++ b/viewpager2/build.gradle @@ -0,0 +1,42 @@ +plugins { + id 'com.android.library' + id 'kotlin-android' +} + +android { + compileSdk 31 + + defaultConfig { + minSdk 23 + targetSdk 31 + versionCode 1 + versionName "1.0" + + testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" + consumerProguardFiles "consumer-rules.pro" + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + kotlinOptions { + jvmTarget = '1.8' + } +} + +dependencies { + + implementation 'com.android.support:appcompat-v7:28.0.0' + api 'com.android.support:recyclerview-v7:28.0.0' + implementation 'android.arch.lifecycle:extensions:1.1.1' + testImplementation 'junit:junit:4.+' + androidTestImplementation 'com.android.support.test:runner:1.0.2' + androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' +} \ No newline at end of file diff --git a/viewpager2/consumer-rules.pro b/viewpager2/consumer-rules.pro new file mode 100644 index 0000000..e69de29 diff --git a/viewpager2/proguard-rules.pro b/viewpager2/proguard-rules.pro new file mode 100644 index 0000000..481bb43 --- /dev/null +++ b/viewpager2/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile \ No newline at end of file diff --git a/viewpager2/src/androidTest/java/com/vinsonguo/viewpager2/ExampleInstrumentedTest.kt b/viewpager2/src/androidTest/java/com/vinsonguo/viewpager2/ExampleInstrumentedTest.kt new file mode 100644 index 0000000..f1ed79c --- /dev/null +++ b/viewpager2/src/androidTest/java/com/vinsonguo/viewpager2/ExampleInstrumentedTest.kt @@ -0,0 +1,24 @@ +package com.vinsonguo.viewpager2 + +import android.support.test.InstrumentationRegistry +import android.support.test.runner.AndroidJUnit4 + +import org.junit.Test +import org.junit.runner.RunWith + +import org.junit.Assert.* + +/** + * Instrumented test, which will execute on an Android device. + * + * See [testing documentation](http://d.android.com/tools/testing). + */ +@RunWith(AndroidJUnit4::class) +class ExampleInstrumentedTest { + @Test + fun useAppContext() { + // Context of the app under test. + val appContext = InstrumentationRegistry.getInstrumentation().targetContext + assertEquals("com.vinsonguo.viewpager2.test", appContext.packageName) + } +} \ No newline at end of file diff --git a/viewpager2/src/main/AndroidManifest.xml b/viewpager2/src/main/AndroidManifest.xml new file mode 100644 index 0000000..705f1e9 --- /dev/null +++ b/viewpager2/src/main/AndroidManifest.xml @@ -0,0 +1,3 @@ + + \ No newline at end of file diff --git a/viewpager2/src/main/java/android/support/v7/widget/ViewPager2LinearLayoutManager.java b/viewpager2/src/main/java/android/support/v7/widget/ViewPager2LinearLayoutManager.java new file mode 100644 index 0000000..3d4f99f --- /dev/null +++ b/viewpager2/src/main/java/android/support/v7/widget/ViewPager2LinearLayoutManager.java @@ -0,0 +1,2550 @@ +package android.support.v7.widget; +import static android.support.annotation.RestrictTo.Scope.LIBRARY; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.graphics.PointF; +import android.os.Parcel; +import android.os.Parcelable; +import android.support.annotation.NonNull; +import android.support.annotation.RestrictTo; +import android.support.v4.os.TraceCompat; +import android.support.v4.view.ViewCompat; +import android.support.v7.widget.LinearSmoothScroller; +import android.support.v7.widget.OrientationHelper; +import android.support.v7.widget.RecyclerView; +import android.support.v7.widget.helper.ItemTouchHelper; +import android.util.AttributeSet; +import android.util.Log; +import android.view.View; +import android.view.ViewGroup; +import android.view.accessibility.AccessibilityEvent; + +import com.vinsonguo.viewpager2.widget.ViewPager2; + +import java.util.List; + +/** + * A {@link RecyclerView.LayoutManager} implementation which provides + * similar functionality to {@link android.widget.ListView}. + */ +public class ViewPager2LinearLayoutManager extends RecyclerView.LayoutManager implements + ItemTouchHelper.ViewDropHandler, RecyclerView.SmoothScroller.ScrollVectorProvider { + + private static final String TAG = "LinearLayoutManager"; + + static final boolean DEBUG = false; + + public static final int HORIZONTAL = RecyclerView.HORIZONTAL; + + public static final int VERTICAL = RecyclerView.VERTICAL; + + public static final int INVALID_OFFSET = Integer.MIN_VALUE; + + + /** + * While trying to find next view to focus, LayoutManager will not try to scroll more + * than this factor times the total space of the list. If layout is vertical, total space is the + * height minus padding, if layout is horizontal, total space is the width minus padding. + */ + private static final float MAX_SCROLL_FACTOR = 1 / 3f; + + /** + * Current orientation. Either {@link #HORIZONTAL} or {@link #VERTICAL} + */ + @RecyclerView.Orientation + int mOrientation = ViewPager2.ORIENTATION_HORIZONTAL; + + /** + * Helper class that keeps temporary layout state. + * It does not keep state after layout is complete but we still keep a reference to re-use + * the same object. + */ + private LayoutState mLayoutState; + + /** + * Many calculations are made depending on orientation. To keep it clean, this interface + * helps {@link LinearLayoutManager} make those decisions. + */ + OrientationHelper mOrientationHelper; + + /** + * We need to track this so that we can ignore current position when it changes. + */ + private boolean mLastStackFromEnd; + + + /** + * Defines if layout should be calculated from end to start. + * + * @see #mShouldReverseLayout + */ + private boolean mReverseLayout = false; + + /** + * This keeps the final value for how LayoutManager should start laying out views. + * It is calculated by checking {@link #getReverseLayout()} and View's layout direction. + * {@link #onLayoutChildren(RecyclerView.Recycler, RecyclerView.State)} is run. + */ + boolean mShouldReverseLayout = false; + + /** + * Works the same way as {@link android.widget.AbsListView#setStackFromBottom(boolean)} and + * it supports both orientations. + * see {@link android.widget.AbsListView#setStackFromBottom(boolean)} + */ + private boolean mStackFromEnd = false; + + /** + * Works the same way as {@link android.widget.AbsListView#setSmoothScrollbarEnabled(boolean)}. + * see {@link android.widget.AbsListView#setSmoothScrollbarEnabled(boolean)} + */ + private boolean mSmoothScrollbarEnabled = true; + + /** + * When LayoutManager needs to scroll to a position, it sets this variable and requests a + * layout which will check this variable and re-layout accordingly. + */ + int mPendingScrollPosition = RecyclerView.NO_POSITION; + + /** + * Used to keep the offset value when {@link #scrollToPositionWithOffset(int, int)} is + * called. + */ + int mPendingScrollPositionOffset = INVALID_OFFSET; + + private boolean mRecycleChildrenOnDetach; + + SavedState mPendingSavedState = null; + + /** + * Re-used variable to keep anchor information on re-layout. + * Anchor position and coordinate defines the reference point for LLM while doing a layout. + * */ + final AnchorInfo mAnchorInfo = new AnchorInfo(); + + /** + * Stashed to avoid allocation, currently only used in #fill() + */ + private final LayoutChunkResult mLayoutChunkResult = new LayoutChunkResult(); + + /** + * Number of items to prefetch when first coming on screen with new data. + */ + private int mInitialPrefetchItemCount = 2; + + // Reusable int array to be passed to method calls that mutate it in order to "return" two ints. + // This should only be used used transiently and should not be used to retain any state over + // time. + private int[] mReusableIntPair = new int[2]; + + /** + * Creates a vertical LinearLayoutManager + * + * @param context Current context, will be used to access resources. + */ + public ViewPager2LinearLayoutManager(Context context) { + this(context, RecyclerView.DEFAULT_ORIENTATION, false); + } + + /** + * @param context Current context, will be used to access resources. + * @param orientation Layout orientation. Should be {@link #HORIZONTAL} or {@link + * #VERTICAL}. + * @param reverseLayout When set to true, layouts from end to start. + */ + public ViewPager2LinearLayoutManager(Context context, @RecyclerView.Orientation int orientation, + boolean reverseLayout) { + setOrientation(orientation); + setReverseLayout(reverseLayout); + } + + /** + * Constructor used when layout manager is set in XML by RecyclerView attribute + * "layoutManager". Defaults to vertical orientation. + * + * {@link android.R.attr#orientation} + * {@link androidx.recyclerview.R.attr#reverseLayout} + * {@link androidx.recyclerview.R.attr#stackFromEnd} + */ + public ViewPager2LinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, + int defStyleRes) { + Properties properties = getProperties(context, attrs, defStyleAttr, defStyleRes); + setOrientation(properties.orientation); + setReverseLayout(properties.reverseLayout); + setStackFromEnd(properties.stackFromEnd); + } + + @Override + public boolean isAutoMeasureEnabled() { + return true; + } + + /** + * {@inheritDoc} + */ + @Override + public RecyclerView.LayoutParams generateDefaultLayoutParams() { + return new RecyclerView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, + ViewGroup.LayoutParams.WRAP_CONTENT); + } + + /** + * Returns whether LayoutManager will recycle its children when it is detached from + * RecyclerView. + * + * @return true if LayoutManager will recycle its children when it is detached from + * RecyclerView. + */ + public boolean getRecycleChildrenOnDetach() { + return mRecycleChildrenOnDetach; + } + + /** + * Set whether LayoutManager will recycle its children when it is detached from + * RecyclerView. + *

+ * If you are using a {@link RecyclerView.RecycledViewPool}, it might be a good idea to set + * this flag to true so that views will be available to other RecyclerViews + * immediately. + *

+ * Note that, setting this flag will result in a performance drop if RecyclerView + * is restored. + * + * @param recycleChildrenOnDetach Whether children should be recycled in detach or not. + */ + public void setRecycleChildrenOnDetach(boolean recycleChildrenOnDetach) { + mRecycleChildrenOnDetach = recycleChildrenOnDetach; + } + + @Override + public void onDetachedFromWindow(RecyclerView view, RecyclerView.Recycler recycler) { + super.onDetachedFromWindow(view, recycler); + if (mRecycleChildrenOnDetach) { + removeAndRecycleAllViews(recycler); + recycler.clear(); + } + } + + @Override + public void onInitializeAccessibilityEvent(AccessibilityEvent event) { + super.onInitializeAccessibilityEvent(event); + if (getChildCount() > 0) { + event.setFromIndex(findFirstVisibleItemPosition()); + event.setToIndex(findLastVisibleItemPosition()); + } + } + + @Override + public Parcelable onSaveInstanceState() { + if (mPendingSavedState != null) { + return new SavedState(mPendingSavedState); + } + SavedState state = new SavedState(); + if (getChildCount() > 0) { + ensureLayoutState(); + boolean didLayoutFromEnd = mLastStackFromEnd ^ mShouldReverseLayout; + state.mAnchorLayoutFromEnd = didLayoutFromEnd; + if (didLayoutFromEnd) { + final View refChild = getChildClosestToEnd(); + state.mAnchorOffset = mOrientationHelper.getEndAfterPadding() + - mOrientationHelper.getDecoratedEnd(refChild); + state.mAnchorPosition = getPosition(refChild); + } else { + final View refChild = getChildClosestToStart(); + state.mAnchorPosition = getPosition(refChild); + state.mAnchorOffset = mOrientationHelper.getDecoratedStart(refChild) + - mOrientationHelper.getStartAfterPadding(); + } + } else { + state.invalidateAnchor(); + } + return state; + } + + @Override + public void onRestoreInstanceState(Parcelable state) { + if (state instanceof SavedState) { + mPendingSavedState = (SavedState) state; + requestLayout(); + if (DEBUG) { + Log.d(TAG, "loaded saved state"); + } + } else if (DEBUG) { + Log.d(TAG, "invalid saved state class"); + } + } + + /** + * @return true if {@link #getOrientation()} is {@link #HORIZONTAL} + */ + @Override + public boolean canScrollHorizontally() { + return mOrientation == HORIZONTAL; + } + + /** + * @return true if {@link #getOrientation()} is {@link #VERTICAL} + */ + @Override + public boolean canScrollVertically() { + return mOrientation == VERTICAL; + } + + /** + * Compatibility support for {@link android.widget.AbsListView#setStackFromBottom(boolean)} + */ + public void setStackFromEnd(boolean stackFromEnd) { + assertNotInLayoutOrScroll(null); + if (mStackFromEnd == stackFromEnd) { + return; + } + mStackFromEnd = stackFromEnd; + requestLayout(); + } + + public boolean getStackFromEnd() { + return mStackFromEnd; + } + + /** + * Returns the current orientation of the layout. + * + * @return Current orientation, either {@link #HORIZONTAL} or {@link #VERTICAL} + * @see #setOrientation(int) + */ + @RecyclerView.Orientation + public int getOrientation() { + return mOrientation; + } + + /** + * Sets the orientation of the layout. {@link LinearLayoutManager} + * will do its best to keep scroll position. + * + * @param orientation {@link #HORIZONTAL} or {@link #VERTICAL} + */ + public void setOrientation(@RecyclerView.Orientation int orientation) { + if (orientation != HORIZONTAL && orientation != VERTICAL) { + throw new IllegalArgumentException("invalid orientation:" + orientation); + } + + assertNotInLayoutOrScroll(null); + + if (orientation != mOrientation || mOrientationHelper == null) { + mOrientationHelper = + OrientationHelper.createOrientationHelper(this, orientation); + mAnchorInfo.mOrientationHelper = mOrientationHelper; + mOrientation = orientation; + requestLayout(); + } + } + + /** + * Calculates the view layout order. (e.g. from end to start or start to end) + * RTL layout support is applied automatically. So if layout is RTL and + * {@link #getReverseLayout()} is {@code true}, elements will be laid out starting from left. + */ + private void resolveShouldLayoutReverse() { + // A == B is the same result, but we rather keep it readable + if (mOrientation == VERTICAL || !isLayoutRTL()) { + mShouldReverseLayout = mReverseLayout; + } else { + mShouldReverseLayout = !mReverseLayout; + } + } + + /** + * Returns if views are laid out from the opposite direction of the layout. + * + * @return If layout is reversed or not. + * @see #setReverseLayout(boolean) + */ + public boolean getReverseLayout() { + return mReverseLayout; + } + + /** + * Used to reverse item traversal and layout order. + * This behaves similar to the layout change for RTL views. When set to true, first item is + * laid out at the end of the UI, second item is laid out before it etc. + * + * For horizontal layouts, it depends on the layout direction. + * When set to true, If {@link RecyclerView} is LTR, than it will + * layout from RTL, if {@link RecyclerView}} is RTL, it will layout + * from LTR. + * + * If you are looking for the exact same behavior of + * {@link android.widget.AbsListView#setStackFromBottom(boolean)}, use + * {@link #setStackFromEnd(boolean)} + */ + public void setReverseLayout(boolean reverseLayout) { + assertNotInLayoutOrScroll(null); + if (reverseLayout == mReverseLayout) { + return; + } + mReverseLayout = reverseLayout; + requestLayout(); + } + + /** + * {@inheritDoc} + */ + @Override + public View findViewByPosition(int position) { + final int childCount = getChildCount(); + if (childCount == 0) { + return null; + } + final int firstChild = getPosition(getChildAt(0)); + final int viewPosition = position - firstChild; + if (viewPosition >= 0 && viewPosition < childCount) { + final View child = getChildAt(viewPosition); + if (getPosition(child) == position) { + return child; // in pre-layout, this may not match + } + } + // fallback to traversal. This might be necessary in pre-layout. + return super.findViewByPosition(position); + } + + /** + *

Returns the amount of extra space that should be laid out by LayoutManager.

+ * + *

By default, {@link LinearLayoutManager} lays out 1 extra page + * of items while smooth scrolling and 0 otherwise. You can override this method to implement + * your custom layout pre-cache logic.

+ * + *

Note:Laying out invisible elements generally comes with significant + * performance cost. It's typically only desirable in places like smooth scrolling to an unknown + * location, where 1) the extra content helps LinearLayoutManager know in advance when its + * target is approaching, so it can decelerate early and smoothly and 2) while motion is + * continuous.

+ * + *

Extending the extra layout space is especially expensive if done while the user may change + * scrolling direction. Changing direction will cause the extra layout space to swap to the + * opposite side of the viewport, incurring many rebinds/recycles, unless the cache is large + * enough to handle it.

+ * + * @return The extra space that should be laid out (in pixels). + * @deprecated Use {@link #calculateExtraLayoutSpace(RecyclerView.State, int[])} instead. + */ + @SuppressWarnings("DeprecatedIsStillUsed") + @Deprecated + protected int getExtraLayoutSpace(RecyclerView.State state) { + if (state.hasTargetScrollPosition()) { + return mOrientationHelper.getTotalSpace(); + } else { + return 0; + } + } + + /** + *

Calculates the amount of extra space (in pixels) that should be laid out by {@link + * LinearLayoutManager} and stores the result in {@code extraLayoutSpace}. {@code + * extraLayoutSpace[0]} should be used for the extra space at the top/left, and {@code + * extraLayoutSpace[1]} should be used for the extra space at the bottom/right (depending on the + * orientation). Thus, the side where it is applied is unaffected by {@link + * #getLayoutDirection()} (LTR vs RTL), {@link #getStackFromEnd()} and {@link + * #getReverseLayout()}. Negative values are ignored.

+ * + *

By default, {@code LinearLayoutManager} lays out 1 extra page of items while smooth + * scrolling, in the direction of the scroll, and no extra space is laid out in all other + * situations. You can override this method to implement your own custom pre-cache logic. Use + * {@link RecyclerView.State#hasTargetScrollPosition()} to find out if a smooth scroll to a + * position is in progress, and {@link RecyclerView.State#getTargetScrollPosition()} to find out + * which item it is scrolling to.

+ * + *

Note:Laying out extra items generally comes with significant performance + * cost. It's typically only desirable in places like smooth scrolling to an unknown location, + * where 1) the extra content helps LinearLayoutManager know in advance when its target is + * approaching, so it can decelerate early and smoothly and 2) while motion is continuous.

+ * + *

Extending the extra layout space is especially expensive if done while the user may change + * scrolling direction. In the default implementation, changing direction will cause the extra + * layout space to swap to the opposite side of the viewport, incurring many rebinds/recycles, + * unless the cache is large enough to handle it.

+ */ + protected void calculateExtraLayoutSpace(@NonNull RecyclerView.State state, + @NonNull int[] extraLayoutSpace) { + int extraLayoutSpaceStart = 0; + int extraLayoutSpaceEnd = 0; + + // If calculateExtraLayoutSpace is not overridden, call the + // deprecated getExtraLayoutSpace for backwards compatibility + @SuppressWarnings("deprecation") + int extraScrollSpace = getExtraLayoutSpace(state); + if (mLayoutState.mLayoutDirection == LayoutState.LAYOUT_START) { + extraLayoutSpaceStart = extraScrollSpace; + } else { + extraLayoutSpaceEnd = extraScrollSpace; + } + + extraLayoutSpace[0] = extraLayoutSpaceStart; + extraLayoutSpace[1] = extraLayoutSpaceEnd; + } + + @Override + public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, + int position) { + LinearSmoothScroller linearSmoothScroller = + new LinearSmoothScroller(recyclerView.getContext()); + linearSmoothScroller.setTargetPosition(position); + startSmoothScroll(linearSmoothScroller); + } + + @Override + public PointF computeScrollVectorForPosition(int targetPosition) { + if (getChildCount() == 0) { + return null; + } + final int firstChildPos = getPosition(getChildAt(0)); + final int direction = targetPosition < firstChildPos != mShouldReverseLayout ? -1 : 1; + if (mOrientation == HORIZONTAL) { + return new PointF(direction, 0); + } else { + return new PointF(0, direction); + } + } + + /** + * {@inheritDoc} + */ + @Override + public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) { + // layout algorithm: + // 1) by checking children and other variables, find an anchor coordinate and an anchor + // item position. + // 2) fill towards start, stacking from bottom + // 3) fill towards end, stacking from top + // 4) scroll to fulfill requirements like stack from bottom. + // create layout state + if (DEBUG) { + Log.d(TAG, "is pre layout:" + state.isPreLayout()); + } + if (mPendingSavedState != null || mPendingScrollPosition != RecyclerView.NO_POSITION) { + if (state.getItemCount() == 0) { + removeAndRecycleAllViews(recycler); + return; + } + } + if (mPendingSavedState != null && mPendingSavedState.hasValidAnchor()) { + mPendingScrollPosition = mPendingSavedState.mAnchorPosition; + } + + ensureLayoutState(); + mLayoutState.mRecycle = false; + // resolve layout direction + resolveShouldLayoutReverse(); + + final View focused = getFocusedChild(); + if (!mAnchorInfo.mValid || mPendingScrollPosition != RecyclerView.NO_POSITION + || mPendingSavedState != null) { + mAnchorInfo.reset(); + mAnchorInfo.mLayoutFromEnd = mShouldReverseLayout ^ mStackFromEnd; + // calculate anchor position and coordinate + updateAnchorInfoForLayout(recycler, state, mAnchorInfo); + mAnchorInfo.mValid = true; + } else if (focused != null && (mOrientationHelper.getDecoratedStart(focused) + >= mOrientationHelper.getEndAfterPadding() + || mOrientationHelper.getDecoratedEnd(focused) + <= mOrientationHelper.getStartAfterPadding())) { + // This case relates to when the anchor child is the focused view and due to layout + // shrinking the focused view fell outside the viewport, e.g. when soft keyboard shows + // up after tapping an EditText which shrinks RV causing the focused view (The tapped + // EditText which is the anchor child) to get kicked out of the screen. Will update the + // anchor coordinate in order to make sure that the focused view is laid out. Otherwise, + // the available space in layoutState will be calculated as negative preventing the + // focused view from being laid out in fill. + // Note that we won't update the anchor position between layout passes (refer to + // TestResizingRelayoutWithAutoMeasure), which happens if we were to call + // updateAnchorInfoForLayout for an anchor that's not the focused view (e.g. a reference + // child which can change between layout passes). + mAnchorInfo.assignFromViewAndKeepVisibleRect(focused, getPosition(focused)); + } + if (DEBUG) { + Log.d(TAG, "Anchor info:" + mAnchorInfo); + } + + // LLM may decide to layout items for "extra" pixels to account for scrolling target, + // caching or predictive animations. + + mLayoutState.mLayoutDirection = mLayoutState.mLastScrollDelta >= 0 + ? LayoutState.LAYOUT_END : LayoutState.LAYOUT_START; + mReusableIntPair[0] = 0; + mReusableIntPair[1] = 0; + calculateExtraLayoutSpace(state, mReusableIntPair); + int extraForStart = Math.max(0, mReusableIntPair[0]) + + mOrientationHelper.getStartAfterPadding(); + int extraForEnd = Math.max(0, mReusableIntPair[1]) + + mOrientationHelper.getEndPadding(); + if (state.isPreLayout() && mPendingScrollPosition != RecyclerView.NO_POSITION + && mPendingScrollPositionOffset != INVALID_OFFSET) { + // if the child is visible and we are going to move it around, we should layout + // extra items in the opposite direction to make sure new items animate nicely + // instead of just fading in + final View existing = findViewByPosition(mPendingScrollPosition); + if (existing != null) { + final int current; + final int upcomingOffset; + if (mShouldReverseLayout) { + current = mOrientationHelper.getEndAfterPadding() + - mOrientationHelper.getDecoratedEnd(existing); + upcomingOffset = current - mPendingScrollPositionOffset; + } else { + current = mOrientationHelper.getDecoratedStart(existing) + - mOrientationHelper.getStartAfterPadding(); + upcomingOffset = mPendingScrollPositionOffset - current; + } + if (upcomingOffset > 0) { + extraForStart += upcomingOffset; + } else { + extraForEnd -= upcomingOffset; + } + } + } + int startOffset; + int endOffset; + final int firstLayoutDirection; + if (mAnchorInfo.mLayoutFromEnd) { + firstLayoutDirection = mShouldReverseLayout ? LayoutState.ITEM_DIRECTION_TAIL + : LayoutState.ITEM_DIRECTION_HEAD; + } else { + firstLayoutDirection = mShouldReverseLayout ? LayoutState.ITEM_DIRECTION_HEAD + : LayoutState.ITEM_DIRECTION_TAIL; + } + + onAnchorReady(recycler, state, mAnchorInfo, firstLayoutDirection); + detachAndScrapAttachedViews(recycler); + mLayoutState.mInfinite = resolveIsInfinite(); + mLayoutState.mIsPreLayout = state.isPreLayout(); + // noRecycleSpace not needed: recycling doesn't happen in below's fill + // invocations because mScrollingOffset is set to SCROLLING_OFFSET_NaN + mLayoutState.mNoRecycleSpace = 0; + if (mAnchorInfo.mLayoutFromEnd) { + // fill towards start + updateLayoutStateToFillStart(mAnchorInfo); + mLayoutState.mExtraFillSpace = extraForStart; + fill(recycler, mLayoutState, state, false); + startOffset = mLayoutState.mOffset; + final int firstElement = mLayoutState.mCurrentPosition; + if (mLayoutState.mAvailable > 0) { + extraForEnd += mLayoutState.mAvailable; + } + // fill towards end + updateLayoutStateToFillEnd(mAnchorInfo); + mLayoutState.mExtraFillSpace = extraForEnd; + mLayoutState.mCurrentPosition += mLayoutState.mItemDirection; + fill(recycler, mLayoutState, state, false); + endOffset = mLayoutState.mOffset; + + if (mLayoutState.mAvailable > 0) { + // end could not consume all. add more items towards start + extraForStart = mLayoutState.mAvailable; + updateLayoutStateToFillStart(firstElement, startOffset); + mLayoutState.mExtraFillSpace = extraForStart; + fill(recycler, mLayoutState, state, false); + startOffset = mLayoutState.mOffset; + } + } else { + // fill towards end + updateLayoutStateToFillEnd(mAnchorInfo); + mLayoutState.mExtraFillSpace = extraForEnd; + fill(recycler, mLayoutState, state, false); + endOffset = mLayoutState.mOffset; + final int lastElement = mLayoutState.mCurrentPosition; + if (mLayoutState.mAvailable > 0) { + extraForStart += mLayoutState.mAvailable; + } + // fill towards start + updateLayoutStateToFillStart(mAnchorInfo); + mLayoutState.mExtraFillSpace = extraForStart; + mLayoutState.mCurrentPosition += mLayoutState.mItemDirection; + fill(recycler, mLayoutState, state, false); + startOffset = mLayoutState.mOffset; + + if (mLayoutState.mAvailable > 0) { + extraForEnd = mLayoutState.mAvailable; + // start could not consume all it should. add more items towards end + updateLayoutStateToFillEnd(lastElement, endOffset); + mLayoutState.mExtraFillSpace = extraForEnd; + fill(recycler, mLayoutState, state, false); + endOffset = mLayoutState.mOffset; + } + } + + // changes may cause gaps on the UI, try to fix them. + // TODO we can probably avoid this if neither stackFromEnd/reverseLayout/RTL values have + // changed + if (getChildCount() > 0) { + // because layout from end may be changed by scroll to position + // we re-calculate it. + // find which side we should check for gaps. + if (mShouldReverseLayout ^ mStackFromEnd) { + int fixOffset = fixLayoutEndGap(endOffset, recycler, state, true); + startOffset += fixOffset; + endOffset += fixOffset; + fixOffset = fixLayoutStartGap(startOffset, recycler, state, false); + startOffset += fixOffset; + endOffset += fixOffset; + } else { + int fixOffset = fixLayoutStartGap(startOffset, recycler, state, true); + startOffset += fixOffset; + endOffset += fixOffset; + fixOffset = fixLayoutEndGap(endOffset, recycler, state, false); + startOffset += fixOffset; + endOffset += fixOffset; + } + } + layoutForPredictiveAnimations(recycler, state, startOffset, endOffset); + if (!state.isPreLayout()) { + mOrientationHelper.onLayoutComplete(); + } else { + mAnchorInfo.reset(); + } + mLastStackFromEnd = mStackFromEnd; + if (DEBUG) { + validateChildOrder(); + } + } + + @Override + public void onLayoutCompleted(RecyclerView.State state) { + super.onLayoutCompleted(state); + mPendingSavedState = null; // we don't need this anymore + mPendingScrollPosition = RecyclerView.NO_POSITION; + mPendingScrollPositionOffset = INVALID_OFFSET; + mAnchorInfo.reset(); + } + + /** + * Method called when Anchor position is decided. Extending class can setup accordingly or + * even update anchor info if necessary. + * @param recycler The recycler for the layout + * @param state The layout state + * @param anchorInfo The mutable POJO that keeps the position and offset. + * @param firstLayoutItemDirection The direction of the first layout filling in terms of adapter + * indices. + */ + void onAnchorReady(RecyclerView.Recycler recycler, RecyclerView.State state, + AnchorInfo anchorInfo, int firstLayoutItemDirection) { + } + + /** + * If necessary, layouts new items for predictive animations + */ + private void layoutForPredictiveAnimations(RecyclerView.Recycler recycler, + RecyclerView.State state, int startOffset, + int endOffset) { + // If there are scrap children that we did not layout, we need to find where they did go + // and layout them accordingly so that animations can work as expected. + // This case may happen if new views are added or an existing view expands and pushes + // another view out of bounds. + if (!state.willRunPredictiveAnimations() || getChildCount() == 0 || state.isPreLayout() + || !supportsPredictiveItemAnimations()) { + return; + } + // to make the logic simpler, we calculate the size of children and call fill. + int scrapExtraStart = 0, scrapExtraEnd = 0; + final List scrapList = recycler.getScrapList(); + final int scrapSize = scrapList.size(); + final int firstChildPos = getPosition(getChildAt(0)); + for (int i = 0; i < scrapSize; i++) { + RecyclerView.ViewHolder scrap = scrapList.get(i); + if (scrap.isRemoved()) { + continue; + } + final int position = scrap.getLayoutPosition(); + final int direction = position < firstChildPos != mShouldReverseLayout + ? LayoutState.LAYOUT_START : LayoutState.LAYOUT_END; + if (direction == LayoutState.LAYOUT_START) { + scrapExtraStart += mOrientationHelper.getDecoratedMeasurement(scrap.itemView); + } else { + scrapExtraEnd += mOrientationHelper.getDecoratedMeasurement(scrap.itemView); + } + } + + if (DEBUG) { + Log.d(TAG, "for unused scrap, decided to add " + scrapExtraStart + + " towards start and " + scrapExtraEnd + " towards end"); + } + mLayoutState.mScrapList = scrapList; + if (scrapExtraStart > 0) { + View anchor = getChildClosestToStart(); + updateLayoutStateToFillStart(getPosition(anchor), startOffset); + mLayoutState.mExtraFillSpace = scrapExtraStart; + mLayoutState.mAvailable = 0; + mLayoutState.assignPositionFromScrapList(); + fill(recycler, mLayoutState, state, false); + } + + if (scrapExtraEnd > 0) { + View anchor = getChildClosestToEnd(); + updateLayoutStateToFillEnd(getPosition(anchor), endOffset); + mLayoutState.mExtraFillSpace = scrapExtraEnd; + mLayoutState.mAvailable = 0; + mLayoutState.assignPositionFromScrapList(); + fill(recycler, mLayoutState, state, false); + } + mLayoutState.mScrapList = null; + } + + private void updateAnchorInfoForLayout(RecyclerView.Recycler recycler, RecyclerView.State state, + AnchorInfo anchorInfo) { + if (updateAnchorFromPendingData(state, anchorInfo)) { + if (DEBUG) { + Log.d(TAG, "updated anchor info from pending information"); + } + return; + } + + if (updateAnchorFromChildren(recycler, state, anchorInfo)) { + if (DEBUG) { + Log.d(TAG, "updated anchor info from existing children"); + } + return; + } + if (DEBUG) { + Log.d(TAG, "deciding anchor info for fresh state"); + } + anchorInfo.assignCoordinateFromPadding(); + anchorInfo.mPosition = mStackFromEnd ? state.getItemCount() - 1 : 0; + } + + /** + * Finds an anchor child from existing Views. Most of the time, this is the view closest to + * start or end that has a valid position (e.g. not removed). + *

+ * If a child has focus, it is given priority. + */ + private boolean updateAnchorFromChildren(RecyclerView.Recycler recycler, + RecyclerView.State state, AnchorInfo anchorInfo) { + if (getChildCount() == 0) { + return false; + } + final View focused = getFocusedChild(); + if (focused != null && anchorInfo.isViewValidAsAnchor(focused, state)) { + anchorInfo.assignFromViewAndKeepVisibleRect(focused, getPosition(focused)); + return true; + } + if (mLastStackFromEnd != mStackFromEnd) { + return false; + } + View referenceChild = anchorInfo.mLayoutFromEnd + ? findReferenceChildClosestToEnd(recycler, state) + : findReferenceChildClosestToStart(recycler, state); + if (referenceChild != null) { + anchorInfo.assignFromView(referenceChild, getPosition(referenceChild)); + // If all visible views are removed in 1 pass, reference child might be out of bounds. + // If that is the case, offset it back to 0 so that we use these pre-layout children. + if (!state.isPreLayout() && supportsPredictiveItemAnimations()) { + // validate this child is at least partially visible. if not, offset it to start + final boolean notVisible = + mOrientationHelper.getDecoratedStart(referenceChild) >= mOrientationHelper + .getEndAfterPadding() + || mOrientationHelper.getDecoratedEnd(referenceChild) + < mOrientationHelper.getStartAfterPadding(); + if (notVisible) { + anchorInfo.mCoordinate = anchorInfo.mLayoutFromEnd + ? mOrientationHelper.getEndAfterPadding() + : mOrientationHelper.getStartAfterPadding(); + } + } + return true; + } + return false; + } + + /** + * If there is a pending scroll position or saved states, updates the anchor info from that + * data and returns true + */ + private boolean updateAnchorFromPendingData(RecyclerView.State state, AnchorInfo anchorInfo) { + if (state.isPreLayout() || mPendingScrollPosition == RecyclerView.NO_POSITION) { + return false; + } + // validate scroll position + if (mPendingScrollPosition < 0 || mPendingScrollPosition >= state.getItemCount()) { + mPendingScrollPosition = RecyclerView.NO_POSITION; + mPendingScrollPositionOffset = INVALID_OFFSET; + if (DEBUG) { + Log.e(TAG, "ignoring invalid scroll position " + mPendingScrollPosition); + } + return false; + } + + // if child is visible, try to make it a reference child and ensure it is fully visible. + // if child is not visible, align it depending on its virtual position. + anchorInfo.mPosition = mPendingScrollPosition; + if (mPendingSavedState != null && mPendingSavedState.hasValidAnchor()) { + // Anchor offset depends on how that child was laid out. Here, we update it + // according to our current view bounds + anchorInfo.mLayoutFromEnd = mPendingSavedState.mAnchorLayoutFromEnd; + if (anchorInfo.mLayoutFromEnd) { + anchorInfo.mCoordinate = mOrientationHelper.getEndAfterPadding() + - mPendingSavedState.mAnchorOffset; + } else { + anchorInfo.mCoordinate = mOrientationHelper.getStartAfterPadding() + + mPendingSavedState.mAnchorOffset; + } + return true; + } + + if (mPendingScrollPositionOffset == INVALID_OFFSET) { + View child = findViewByPosition(mPendingScrollPosition); + if (child != null) { + final int childSize = mOrientationHelper.getDecoratedMeasurement(child); + if (childSize > mOrientationHelper.getTotalSpace()) { + // item does not fit. fix depending on layout direction + anchorInfo.assignCoordinateFromPadding(); + return true; + } + final int startGap = mOrientationHelper.getDecoratedStart(child) + - mOrientationHelper.getStartAfterPadding(); + if (startGap < 0) { + anchorInfo.mCoordinate = mOrientationHelper.getStartAfterPadding(); + anchorInfo.mLayoutFromEnd = false; + return true; + } + final int endGap = mOrientationHelper.getEndAfterPadding() + - mOrientationHelper.getDecoratedEnd(child); + if (endGap < 0) { + anchorInfo.mCoordinate = mOrientationHelper.getEndAfterPadding(); + anchorInfo.mLayoutFromEnd = true; + return true; + } + anchorInfo.mCoordinate = anchorInfo.mLayoutFromEnd + ? (mOrientationHelper.getDecoratedEnd(child) + mOrientationHelper + .getTotalSpaceChange()) + : mOrientationHelper.getDecoratedStart(child); + } else { // item is not visible. + if (getChildCount() > 0) { + // get position of any child, does not matter + int pos = getPosition(getChildAt(0)); + anchorInfo.mLayoutFromEnd = mPendingScrollPosition < pos + == mShouldReverseLayout; + } + anchorInfo.assignCoordinateFromPadding(); + } + return true; + } + // override layout from end values for consistency + anchorInfo.mLayoutFromEnd = mShouldReverseLayout; + // if this changes, we should update prepareForDrop as well + if (mShouldReverseLayout) { + anchorInfo.mCoordinate = mOrientationHelper.getEndAfterPadding() + - mPendingScrollPositionOffset; + } else { + anchorInfo.mCoordinate = mOrientationHelper.getStartAfterPadding() + + mPendingScrollPositionOffset; + } + return true; + } + + /** + * @return The final offset amount for children + */ + private int fixLayoutEndGap(int endOffset, RecyclerView.Recycler recycler, + RecyclerView.State state, boolean canOffsetChildren) { + int gap = mOrientationHelper.getEndAfterPadding() - endOffset; + int fixOffset = 0; + if (gap > 0) { + fixOffset = -scrollBy(-gap, recycler, state); + } else { + return 0; // nothing to fix + } + // move offset according to scroll amount + endOffset += fixOffset; + if (canOffsetChildren) { + // re-calculate gap, see if we could fix it + gap = mOrientationHelper.getEndAfterPadding() - endOffset; + if (gap > 0) { + mOrientationHelper.offsetChildren(gap); + return gap + fixOffset; + } + } + return fixOffset; + } + + /** + * @return The final offset amount for children + */ + private int fixLayoutStartGap(int startOffset, RecyclerView.Recycler recycler, + RecyclerView.State state, boolean canOffsetChildren) { + int gap = startOffset - mOrientationHelper.getStartAfterPadding(); + int fixOffset = 0; + if (gap > 0) { + // check if we should fix this gap. + fixOffset = -scrollBy(gap, recycler, state); + } else { + return 0; // nothing to fix + } + startOffset += fixOffset; + if (canOffsetChildren) { + // re-calculate gap, see if we could fix it + gap = startOffset - mOrientationHelper.getStartAfterPadding(); + if (gap > 0) { + mOrientationHelper.offsetChildren(-gap); + return fixOffset - gap; + } + } + return fixOffset; + } + + private void updateLayoutStateToFillEnd(AnchorInfo anchorInfo) { + updateLayoutStateToFillEnd(anchorInfo.mPosition, anchorInfo.mCoordinate); + } + + private void updateLayoutStateToFillEnd(int itemPosition, int offset) { + mLayoutState.mAvailable = mOrientationHelper.getEndAfterPadding() - offset; + mLayoutState.mItemDirection = mShouldReverseLayout ? LayoutState.ITEM_DIRECTION_HEAD : + LayoutState.ITEM_DIRECTION_TAIL; + mLayoutState.mCurrentPosition = itemPosition; + mLayoutState.mLayoutDirection = LayoutState.LAYOUT_END; + mLayoutState.mOffset = offset; + mLayoutState.mScrollingOffset = LayoutState.SCROLLING_OFFSET_NaN; + } + + private void updateLayoutStateToFillStart(AnchorInfo anchorInfo) { + updateLayoutStateToFillStart(anchorInfo.mPosition, anchorInfo.mCoordinate); + } + + private void updateLayoutStateToFillStart(int itemPosition, int offset) { + mLayoutState.mAvailable = offset - mOrientationHelper.getStartAfterPadding(); + mLayoutState.mCurrentPosition = itemPosition; + mLayoutState.mItemDirection = mShouldReverseLayout ? LayoutState.ITEM_DIRECTION_TAIL : + LayoutState.ITEM_DIRECTION_HEAD; + mLayoutState.mLayoutDirection = LayoutState.LAYOUT_START; + mLayoutState.mOffset = offset; + mLayoutState.mScrollingOffset = LayoutState.SCROLLING_OFFSET_NaN; + + } + + protected boolean isLayoutRTL() { + return getLayoutDirection() == ViewCompat.LAYOUT_DIRECTION_RTL; + } + + void ensureLayoutState() { + if (mLayoutState == null) { + mLayoutState = createLayoutState(); + } + } + + /** + * Test overrides this to plug some tracking and verification. + * + * @return A new LayoutState + */ + LayoutState createLayoutState() { + return new LayoutState(); + } + + /** + *

Scroll the RecyclerView to make the position visible.

+ * + *

RecyclerView will scroll the minimum amount that is necessary to make the + * target position visible. If you are looking for a similar behavior to + * {@link android.widget.ListView#setSelection(int)} or + * {@link android.widget.ListView#setSelectionFromTop(int, int)}, use + * {@link #scrollToPositionWithOffset(int, int)}.

+ * + *

Note that scroll position change will not be reflected until the next layout call.

+ * + * @param position Scroll to this adapter position + * @see #scrollToPositionWithOffset(int, int) + */ + @Override + public void scrollToPosition(int position) { + mPendingScrollPosition = position; + mPendingScrollPositionOffset = INVALID_OFFSET; + if (mPendingSavedState != null) { + mPendingSavedState.invalidateAnchor(); + } + requestLayout(); + } + + /** + * Scroll to the specified adapter position with the given offset from resolved layout + * start. Resolved layout start depends on {@link #getReverseLayout()}, + * {@link ViewCompat#getLayoutDirection(android.view.View)} and {@link #getStackFromEnd()}. + *

+ * For example, if layout is {@link #VERTICAL} and {@link #getStackFromEnd()} is true, calling + * scrollToPositionWithOffset(10, 20) will layout such that + * item[10]'s bottom is 20 pixels above the RecyclerView's bottom. + *

+ * Note that scroll position change will not be reflected until the next layout call. + *

+ * If you are just trying to make a position visible, use {@link #scrollToPosition(int)}. + * + * @param position Index (starting at 0) of the reference item. + * @param offset The distance (in pixels) between the start edge of the item view and + * start edge of the RecyclerView. + * @see #setReverseLayout(boolean) + * @see #scrollToPosition(int) + */ + public void scrollToPositionWithOffset(int position, int offset) { + mPendingScrollPosition = position; + mPendingScrollPositionOffset = offset; + if (mPendingSavedState != null) { + mPendingSavedState.invalidateAnchor(); + } + requestLayout(); + } + + + /** + * {@inheritDoc} + */ + @Override + public int scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler, + RecyclerView.State state) { + if (mOrientation == VERTICAL) { + return 0; + } + return scrollBy(dx, recycler, state); + } + + /** + * {@inheritDoc} + */ + @Override + public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, + RecyclerView.State state) { + if (mOrientation == HORIZONTAL) { + return 0; + } + return scrollBy(dy, recycler, state); + } + + @Override + public int computeHorizontalScrollOffset(RecyclerView.State state) { + return computeScrollOffset(state); + } + + @Override + public int computeVerticalScrollOffset(RecyclerView.State state) { + return computeScrollOffset(state); + } + + @Override + public int computeHorizontalScrollExtent(RecyclerView.State state) { + return computeScrollExtent(state); + } + + @Override + public int computeVerticalScrollExtent(RecyclerView.State state) { + return computeScrollExtent(state); + } + + @Override + public int computeHorizontalScrollRange(RecyclerView.State state) { + return computeScrollRange(state); + } + + @Override + public int computeVerticalScrollRange(RecyclerView.State state) { + return computeScrollRange(state); + } + + private int computeScrollOffset(RecyclerView.State state) { + if (getChildCount() == 0) { + return 0; + } + ensureLayoutState(); + return ScrollbarHelper.computeScrollOffset(state, mOrientationHelper, + findFirstVisibleChildClosestToStart(!mSmoothScrollbarEnabled, true), + findFirstVisibleChildClosestToEnd(!mSmoothScrollbarEnabled, true), + this, mSmoothScrollbarEnabled, mShouldReverseLayout); + } + + private int computeScrollExtent(RecyclerView.State state) { + if (getChildCount() == 0) { + return 0; + } + ensureLayoutState(); + return ScrollbarHelper.computeScrollExtent(state, mOrientationHelper, + findFirstVisibleChildClosestToStart(!mSmoothScrollbarEnabled, true), + findFirstVisibleChildClosestToEnd(!mSmoothScrollbarEnabled, true), + this, mSmoothScrollbarEnabled); + } + + private int computeScrollRange(RecyclerView.State state) { + if (getChildCount() == 0) { + return 0; + } + ensureLayoutState(); + return ScrollbarHelper.computeScrollRange(state, mOrientationHelper, + findFirstVisibleChildClosestToStart(!mSmoothScrollbarEnabled, true), + findFirstVisibleChildClosestToEnd(!mSmoothScrollbarEnabled, true), + this, mSmoothScrollbarEnabled); + } + + /** + * When smooth scrollbar is enabled, the position and size of the scrollbar thumb is computed + * based on the number of visible pixels in the visible items. This however assumes that all + * list items have similar or equal widths or heights (depending on list orientation). + * If you use a list in which items have different dimensions, the scrollbar will change + * appearance as the user scrolls through the list. To avoid this issue, you need to disable + * this property. + * + * When smooth scrollbar is disabled, the position and size of the scrollbar thumb is based + * solely on the number of items in the adapter and the position of the visible items inside + * the adapter. This provides a stable scrollbar as the user navigates through a list of items + * with varying widths / heights. + * + * @param enabled Whether or not to enable smooth scrollbar. + * + * @see #setSmoothScrollbarEnabled(boolean) + */ + public void setSmoothScrollbarEnabled(boolean enabled) { + mSmoothScrollbarEnabled = enabled; + } + + /** + * Returns the current state of the smooth scrollbar feature. It is enabled by default. + * + * @return True if smooth scrollbar is enabled, false otherwise. + * + * @see #setSmoothScrollbarEnabled(boolean) + */ + public boolean isSmoothScrollbarEnabled() { + return mSmoothScrollbarEnabled; + } + + private void updateLayoutState(int layoutDirection, int requiredSpace, + boolean canUseExistingSpace, RecyclerView.State state) { + // If parent provides a hint, don't measure unlimited. + mLayoutState.mInfinite = resolveIsInfinite(); + mLayoutState.mLayoutDirection = layoutDirection; + mReusableIntPair[0] = 0; + mReusableIntPair[1] = 0; + calculateExtraLayoutSpace(state, mReusableIntPair); + int extraForStart = Math.max(0, mReusableIntPair[0]); + int extraForEnd = Math.max(0, mReusableIntPair[1]); + boolean layoutToEnd = layoutDirection == LayoutState.LAYOUT_END; + mLayoutState.mExtraFillSpace = layoutToEnd ? extraForEnd : extraForStart; + mLayoutState.mNoRecycleSpace = layoutToEnd ? extraForStart : extraForEnd; + int scrollingOffset; + if (layoutToEnd) { + mLayoutState.mExtraFillSpace += mOrientationHelper.getEndPadding(); + // get the first child in the direction we are going + final View child = getChildClosestToEnd(); + // the direction in which we are traversing children + mLayoutState.mItemDirection = mShouldReverseLayout ? LayoutState.ITEM_DIRECTION_HEAD + : LayoutState.ITEM_DIRECTION_TAIL; + mLayoutState.mCurrentPosition = getPosition(child) + mLayoutState.mItemDirection; + mLayoutState.mOffset = mOrientationHelper.getDecoratedEnd(child); + // calculate how much we can scroll without adding new children (independent of layout) + scrollingOffset = mOrientationHelper.getDecoratedEnd(child) + - mOrientationHelper.getEndAfterPadding(); + + } else { + final View child = getChildClosestToStart(); + mLayoutState.mExtraFillSpace += mOrientationHelper.getStartAfterPadding(); + mLayoutState.mItemDirection = mShouldReverseLayout ? LayoutState.ITEM_DIRECTION_TAIL + : LayoutState.ITEM_DIRECTION_HEAD; + mLayoutState.mCurrentPosition = getPosition(child) + mLayoutState.mItemDirection; + mLayoutState.mOffset = mOrientationHelper.getDecoratedStart(child); + scrollingOffset = -mOrientationHelper.getDecoratedStart(child) + + mOrientationHelper.getStartAfterPadding(); + } + mLayoutState.mAvailable = requiredSpace; + if (canUseExistingSpace) { + mLayoutState.mAvailable -= scrollingOffset; + } + mLayoutState.mScrollingOffset = scrollingOffset; + } + + boolean resolveIsInfinite() { + return mOrientationHelper.getMode() == View.MeasureSpec.UNSPECIFIED + && mOrientationHelper.getEnd() == 0; + } + + void collectPrefetchPositionsForLayoutState(RecyclerView.State state, LayoutState layoutState, + LayoutPrefetchRegistry layoutPrefetchRegistry) { + final int pos = layoutState.mCurrentPosition; + if (pos >= 0 && pos < state.getItemCount()) { + layoutPrefetchRegistry.addPosition(pos, Math.max(0, layoutState.mScrollingOffset)); + } + } + + @Override + public void collectInitialPrefetchPositions(int adapterItemCount, + LayoutPrefetchRegistry layoutPrefetchRegistry) { + final boolean fromEnd; + final int anchorPos; + if (mPendingSavedState != null && mPendingSavedState.hasValidAnchor()) { + // use restored state, since it hasn't been resolved yet + fromEnd = mPendingSavedState.mAnchorLayoutFromEnd; + anchorPos = mPendingSavedState.mAnchorPosition; + } else { + resolveShouldLayoutReverse(); + fromEnd = mShouldReverseLayout; + if (mPendingScrollPosition == RecyclerView.NO_POSITION) { + anchorPos = fromEnd ? adapterItemCount - 1 : 0; + } else { + anchorPos = mPendingScrollPosition; + } + } + + final int direction = fromEnd + ? LayoutState.ITEM_DIRECTION_HEAD + : LayoutState.ITEM_DIRECTION_TAIL; + int targetPos = anchorPos; + for (int i = 0; i < mInitialPrefetchItemCount; i++) { + if (targetPos >= 0 && targetPos < adapterItemCount) { + layoutPrefetchRegistry.addPosition(targetPos, 0); + } else { + break; // no more to prefetch + } + targetPos += direction; + } + } + + /** + * Sets the number of items to prefetch in + * {@link #collectInitialPrefetchPositions(int, LayoutPrefetchRegistry)}, which defines + * how many inner items should be prefetched when this LayoutManager's RecyclerView + * is nested inside another RecyclerView. + * + *

Set this value to the number of items this inner LayoutManager will display when it is + * first scrolled into the viewport. RecyclerView will attempt to prefetch that number of items + * so they are ready, avoiding jank as the inner RecyclerView is scrolled into the viewport.

+ * + *

For example, take a vertically scrolling RecyclerView with horizontally scrolling inner + * RecyclerViews. The rows always have 4 items visible in them (or 5 if not aligned). Passing + * 4 to this method for each inner RecyclerView's LinearLayoutManager will enable + * RecyclerView's prefetching feature to do create/bind work for 4 views within a row early, + * before it is scrolled on screen, instead of just the default 2.

+ * + *

Calling this method does nothing unless the LayoutManager is in a RecyclerView + * nested in another RecyclerView.

+ * + *

Note: Setting this value to be larger than the number of + * views that will be visible in this view can incur unnecessary bind work, and an increase to + * the number of Views created and in active use.

+ * + * @param itemCount Number of items to prefetch + * + * @see #isItemPrefetchEnabled() + * @see #getInitialPrefetchItemCount() + * @see #collectInitialPrefetchPositions(int, LayoutPrefetchRegistry) + */ + public void setInitialPrefetchItemCount(int itemCount) { + mInitialPrefetchItemCount = itemCount; + } + + /** + * Gets the number of items to prefetch in + * {@link #collectInitialPrefetchPositions(int, LayoutPrefetchRegistry)}, which defines + * how many inner items should be prefetched when this LayoutManager's RecyclerView + * is nested inside another RecyclerView. + * + * @see #isItemPrefetchEnabled() + * @see #setInitialPrefetchItemCount(int) + * @see #collectInitialPrefetchPositions(int, LayoutPrefetchRegistry) + * + * @return number of items to prefetch. + */ + public int getInitialPrefetchItemCount() { + return mInitialPrefetchItemCount; + } + + @Override + public void collectAdjacentPrefetchPositions(int dx, int dy, RecyclerView.State state, + LayoutPrefetchRegistry layoutPrefetchRegistry) { + int delta = (mOrientation == HORIZONTAL) ? dx : dy; + if (getChildCount() == 0 || delta == 0) { + // can't support this scroll, so don't bother prefetching + return; + } + + ensureLayoutState(); + final int layoutDirection = delta > 0 ? LayoutState.LAYOUT_END : LayoutState.LAYOUT_START; + final int absDelta = Math.abs(delta); + updateLayoutState(layoutDirection, absDelta, true, state); + collectPrefetchPositionsForLayoutState(state, mLayoutState, layoutPrefetchRegistry); + } + + int scrollBy(int delta, RecyclerView.Recycler recycler, RecyclerView.State state) { + if (getChildCount() == 0 || delta == 0) { + return 0; + } + ensureLayoutState(); + mLayoutState.mRecycle = true; + final int layoutDirection = delta > 0 ? LayoutState.LAYOUT_END : LayoutState.LAYOUT_START; + final int absDelta = Math.abs(delta); + updateLayoutState(layoutDirection, absDelta, true, state); + final int consumed = mLayoutState.mScrollingOffset + + fill(recycler, mLayoutState, state, false); + if (consumed < 0) { + if (DEBUG) { + Log.d(TAG, "Don't have any more elements to scroll"); + } + return 0; + } + final int scrolled = absDelta > consumed ? layoutDirection * consumed : delta; + mOrientationHelper.offsetChildren(-scrolled); + if (DEBUG) { + Log.d(TAG, "scroll req: " + delta + " scrolled: " + scrolled); + } + mLayoutState.mLastScrollDelta = scrolled; + return scrolled; + } + + @Override + public void assertNotInLayoutOrScroll(String message) { + if (mPendingSavedState == null) { + super.assertNotInLayoutOrScroll(message); + } + } + + /** + * Recycles children between given indices. + * + * @param startIndex inclusive + * @param endIndex exclusive + */ + private void recycleChildren(RecyclerView.Recycler recycler, int startIndex, int endIndex) { + if (startIndex == endIndex) { + return; + } + if (DEBUG) { + Log.d(TAG, "Recycling " + Math.abs(startIndex - endIndex) + " items"); + } + if (endIndex > startIndex) { + for (int i = endIndex - 1; i >= startIndex; i--) { + removeAndRecycleViewAt(i, recycler); + } + } else { + for (int i = startIndex; i > endIndex; i--) { + removeAndRecycleViewAt(i, recycler); + } + } + } + + /** + * Recycles views that went out of bounds after scrolling towards the end of the layout. + *

+ * Checks both layout position and visible position to guarantee that the view is not visible. + * + * @param recycler Recycler instance of {@link RecyclerView} + * @param scrollingOffset This can be used to add additional padding to the visible area. This + * is used to detect children that will go out of bounds after scrolling, + * without actually moving them. + * @param noRecycleSpace Extra space that should be excluded from recycling. This is the space + * from {@code extraLayoutSpace[0]}, calculated in {@link + * #calculateExtraLayoutSpace}. + */ + private void recycleViewsFromStart(RecyclerView.Recycler recycler, int scrollingOffset, + int noRecycleSpace) { + if (scrollingOffset < 0) { + if (DEBUG) { + Log.d(TAG, "Called recycle from start with a negative value. This might happen" + + " during layout changes but may be sign of a bug"); + } + return; + } + // ignore padding, ViewGroup may not clip children. + final int limit = scrollingOffset - noRecycleSpace; + final int childCount = getChildCount(); + if (mShouldReverseLayout) { + for (int i = childCount - 1; i >= 0; i--) { + View child = getChildAt(i); + if (mOrientationHelper.getDecoratedEnd(child) > limit + || mOrientationHelper.getTransformedEndWithDecoration(child) > limit) { + // stop here + recycleChildren(recycler, childCount - 1, i); + return; + } + } + } else { + for (int i = 0; i < childCount; i++) { + View child = getChildAt(i); + if (mOrientationHelper.getDecoratedEnd(child) > limit + || mOrientationHelper.getTransformedEndWithDecoration(child) > limit) { + // stop here + recycleChildren(recycler, 0, i); + return; + } + } + } + } + + + /** + * Recycles views that went out of bounds after scrolling towards the start of the layout. + *

+ * Checks both layout position and visible position to guarantee that the view is not visible. + * + * @param recycler Recycler instance of {@link RecyclerView} + * @param scrollingOffset This can be used to add additional padding to the visible area. This + * is used to detect children that will go out of bounds after scrolling, + * without actually moving them. + * @param noRecycleSpace Extra space that should be excluded from recycling. This is the space + * from {@code extraLayoutSpace[1]}, calculated in {@link + * #calculateExtraLayoutSpace}. + */ + private void recycleViewsFromEnd(RecyclerView.Recycler recycler, int scrollingOffset, + int noRecycleSpace) { + final int childCount = getChildCount(); + if (scrollingOffset < 0) { + if (DEBUG) { + Log.d(TAG, "Called recycle from end with a negative value. This might happen" + + " during layout changes but may be sign of a bug"); + } + return; + } + final int limit = mOrientationHelper.getEnd() - scrollingOffset + noRecycleSpace; + if (mShouldReverseLayout) { + for (int i = 0; i < childCount; i++) { + View child = getChildAt(i); + if (mOrientationHelper.getDecoratedStart(child) < limit + || mOrientationHelper.getTransformedStartWithDecoration(child) < limit) { + // stop here + recycleChildren(recycler, 0, i); + return; + } + } + } else { + for (int i = childCount - 1; i >= 0; i--) { + View child = getChildAt(i); + if (mOrientationHelper.getDecoratedStart(child) < limit + || mOrientationHelper.getTransformedStartWithDecoration(child) < limit) { + // stop here + recycleChildren(recycler, childCount - 1, i); + return; + } + } + } + } + + /** + * Helper method to call appropriate recycle method depending on current layout direction + * + * @param recycler Current recycler that is attached to RecyclerView + * @param layoutState Current layout state. Right now, this object does not change but + * we may consider moving it out of this view so passing around as a + * parameter for now, rather than accessing {@link #mLayoutState} + * @see #recycleViewsFromStart(RecyclerView.Recycler, int, int) + * @see #recycleViewsFromEnd(RecyclerView.Recycler, int, int) + * @see LinearLayoutManager.LayoutState#mLayoutDirection + */ + private void recycleByLayoutState(RecyclerView.Recycler recycler, LayoutState layoutState) { + if (!layoutState.mRecycle || layoutState.mInfinite) { + return; + } + int scrollingOffset = layoutState.mScrollingOffset; + int noRecycleSpace = layoutState.mNoRecycleSpace; + if (layoutState.mLayoutDirection == LayoutState.LAYOUT_START) { + recycleViewsFromEnd(recycler, scrollingOffset, noRecycleSpace); + } else { + recycleViewsFromStart(recycler, scrollingOffset, noRecycleSpace); + } + } + + /** + * The magic functions :). Fills the given layout, defined by the layoutState. This is fairly + * independent from the rest of the {@link LinearLayoutManager} + * and with little change, can be made publicly available as a helper class. + * + * @param recycler Current recycler that is attached to RecyclerView + * @param layoutState Configuration on how we should fill out the available space. + * @param state Context passed by the RecyclerView to control scroll steps. + * @param stopOnFocusable If true, filling stops in the first focusable new child + * @return Number of pixels that it added. Useful for scroll functions. + */ + int fill(RecyclerView.Recycler recycler, LayoutState layoutState, + RecyclerView.State state, boolean stopOnFocusable) { + // max offset we should set is mFastScroll + available + final int start = layoutState.mAvailable; + if (layoutState.mScrollingOffset != LayoutState.SCROLLING_OFFSET_NaN) { + // TODO ugly bug fix. should not happen + if (layoutState.mAvailable < 0) { + layoutState.mScrollingOffset += layoutState.mAvailable; + } + recycleByLayoutState(recycler, layoutState); + } + int remainingSpace = layoutState.mAvailable + layoutState.mExtraFillSpace; + LayoutChunkResult layoutChunkResult = mLayoutChunkResult; + while ((layoutState.mInfinite || remainingSpace > 0) && layoutState.hasMore(state)) { + layoutChunkResult.resetInternal(); + if (RecyclerView.VERBOSE_TRACING) { + TraceCompat.beginSection("LLM LayoutChunk"); + } + layoutChunk(recycler, state, layoutState, layoutChunkResult); + if (RecyclerView.VERBOSE_TRACING) { + TraceCompat.endSection(); + } + if (layoutChunkResult.mFinished) { + break; + } + layoutState.mOffset += layoutChunkResult.mConsumed * layoutState.mLayoutDirection; + /** + * Consume the available space if: + * * layoutChunk did not request to be ignored + * * OR we are laying out scrap children + * * OR we are not doing pre-layout + */ + if (!layoutChunkResult.mIgnoreConsumed || layoutState.mScrapList != null + || !state.isPreLayout()) { + layoutState.mAvailable -= layoutChunkResult.mConsumed; + // we keep a separate remaining space because mAvailable is important for recycling + remainingSpace -= layoutChunkResult.mConsumed; + } + + if (layoutState.mScrollingOffset != LayoutState.SCROLLING_OFFSET_NaN) { + layoutState.mScrollingOffset += layoutChunkResult.mConsumed; + if (layoutState.mAvailable < 0) { + layoutState.mScrollingOffset += layoutState.mAvailable; + } + recycleByLayoutState(recycler, layoutState); + } + if (stopOnFocusable && layoutChunkResult.mFocusable) { + break; + } + } + if (DEBUG) { + validateChildOrder(); + } + return start - layoutState.mAvailable; + } + + void layoutChunk(RecyclerView.Recycler recycler, RecyclerView.State state, + LayoutState layoutState, LayoutChunkResult result) { + View view = layoutState.next(recycler); + if (view == null) { + if (DEBUG && layoutState.mScrapList == null) { + throw new RuntimeException("received null view when unexpected"); + } + // if we are laying out views in scrap, this may return null which means there is + // no more items to layout. + result.mFinished = true; + return; + } + RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) view.getLayoutParams(); + if (layoutState.mScrapList == null) { + if (mShouldReverseLayout == (layoutState.mLayoutDirection + == LayoutState.LAYOUT_START)) { + addView(view); + } else { + addView(view, 0); + } + } else { + if (mShouldReverseLayout == (layoutState.mLayoutDirection + == LayoutState.LAYOUT_START)) { + addDisappearingView(view); + } else { + addDisappearingView(view, 0); + } + } + measureChildWithMargins(view, 0, 0); + result.mConsumed = mOrientationHelper.getDecoratedMeasurement(view); + int left, top, right, bottom; + if (mOrientation == VERTICAL) { + if (isLayoutRTL()) { + right = getWidth() - getPaddingRight(); + left = right - mOrientationHelper.getDecoratedMeasurementInOther(view); + } else { + left = getPaddingLeft(); + right = left + mOrientationHelper.getDecoratedMeasurementInOther(view); + } + if (layoutState.mLayoutDirection == LayoutState.LAYOUT_START) { + bottom = layoutState.mOffset; + top = layoutState.mOffset - result.mConsumed; + } else { + top = layoutState.mOffset; + bottom = layoutState.mOffset + result.mConsumed; + } + } else { + top = getPaddingTop(); + bottom = top + mOrientationHelper.getDecoratedMeasurementInOther(view); + + if (layoutState.mLayoutDirection == LayoutState.LAYOUT_START) { + right = layoutState.mOffset; + left = layoutState.mOffset - result.mConsumed; + } else { + left = layoutState.mOffset; + right = layoutState.mOffset + result.mConsumed; + } + } + // We calculate everything with View's bounding box (which includes decor and margins) + // To calculate correct layout position, we subtract margins. + layoutDecoratedWithMargins(view, left, top, right, bottom); + if (DEBUG) { + Log.d(TAG, "laid out child at position " + getPosition(view) + ", with l:" + + (left + params.leftMargin) + ", t:" + (top + params.topMargin) + ", r:" + + (right - params.rightMargin) + ", b:" + (bottom - params.bottomMargin)); + } + // Consume the available space if the view is not removed OR changed + if (params.isItemRemoved() || params.isItemChanged()) { + result.mIgnoreConsumed = true; + } + result.mFocusable = view.hasFocusable(); + } + + @Override + boolean shouldMeasureTwice() { + return getHeightMode() != View.MeasureSpec.EXACTLY + && getWidthMode() != View.MeasureSpec.EXACTLY + && hasFlexibleChildInBothOrientations(); + } + + /** + * Converts a focusDirection to orientation. + * + * @param focusDirection One of {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, + * {@link View#FOCUS_LEFT}, {@link View#FOCUS_RIGHT}, + * {@link View#FOCUS_BACKWARD}, {@link View#FOCUS_FORWARD} + * or 0 for not applicable + * @return {@link LayoutState#LAYOUT_START} or {@link LayoutState#LAYOUT_END} if focus direction + * is applicable to current state, {@link LayoutState#INVALID_LAYOUT} otherwise. + */ + int convertFocusDirectionToLayoutDirection(int focusDirection) { + switch (focusDirection) { + case View.FOCUS_BACKWARD: + if (mOrientation == VERTICAL) { + return LayoutState.LAYOUT_START; + } else if (isLayoutRTL()) { + return LayoutState.LAYOUT_END; + } else { + return LayoutState.LAYOUT_START; + } + case View.FOCUS_FORWARD: + if (mOrientation == VERTICAL) { + return LayoutState.LAYOUT_END; + } else if (isLayoutRTL()) { + return LayoutState.LAYOUT_START; + } else { + return LayoutState.LAYOUT_END; + } + case View.FOCUS_UP: + return mOrientation == VERTICAL ? LayoutState.LAYOUT_START + : LayoutState.INVALID_LAYOUT; + case View.FOCUS_DOWN: + return mOrientation == VERTICAL ? LayoutState.LAYOUT_END + : LayoutState.INVALID_LAYOUT; + case View.FOCUS_LEFT: + return mOrientation == HORIZONTAL ? LayoutState.LAYOUT_START + : LayoutState.INVALID_LAYOUT; + case View.FOCUS_RIGHT: + return mOrientation == HORIZONTAL ? LayoutState.LAYOUT_END + : LayoutState.INVALID_LAYOUT; + default: + if (DEBUG) { + Log.d(TAG, "Unknown focus request:" + focusDirection); + } + return LayoutState.INVALID_LAYOUT; + } + + } + + /** + * Convenience method to find the child closes to start. Caller should check it has enough + * children. + * + * @return The child closes to start of the layout from user's perspective. + */ + private View getChildClosestToStart() { + return getChildAt(mShouldReverseLayout ? getChildCount() - 1 : 0); + } + + /** + * Convenience method to find the child closes to end. Caller should check it has enough + * children. + * + * @return The child closes to end of the layout from user's perspective. + */ + private View getChildClosestToEnd() { + return getChildAt(mShouldReverseLayout ? 0 : getChildCount() - 1); + } + + /** + * Convenience method to find the visible child closes to start. Caller should check if it has + * enough children. + * + * @param completelyVisible Whether child should be completely visible or not + * @return The first visible child closest to start of the layout from user's perspective. + */ + View findFirstVisibleChildClosestToStart(boolean completelyVisible, + boolean acceptPartiallyVisible) { + if (mShouldReverseLayout) { + return findOneVisibleChild(getChildCount() - 1, -1, completelyVisible, + acceptPartiallyVisible); + } else { + return findOneVisibleChild(0, getChildCount(), completelyVisible, + acceptPartiallyVisible); + } + } + + /** + * Convenience method to find the visible child closes to end. Caller should check if it has + * enough children. + * + * @param completelyVisible Whether child should be completely visible or not + * @return The first visible child closest to end of the layout from user's perspective. + */ + View findFirstVisibleChildClosestToEnd(boolean completelyVisible, + boolean acceptPartiallyVisible) { + if (mShouldReverseLayout) { + return findOneVisibleChild(0, getChildCount(), completelyVisible, + acceptPartiallyVisible); + } else { + return findOneVisibleChild(getChildCount() - 1, -1, completelyVisible, + acceptPartiallyVisible); + } + } + + + /** + * Among the children that are suitable to be considered as an anchor child, returns the one + * closest to the end of the layout. + *

+ * Due to ambiguous adapter updates or children being removed, some children's positions may be + * invalid. This method is a best effort to find a position within adapter bounds if possible. + *

+ * It also prioritizes children that are within the visible bounds. + * @return A View that can be used an an anchor View. + */ + private View findReferenceChildClosestToEnd(RecyclerView.Recycler recycler, + RecyclerView.State state) { + return mShouldReverseLayout ? findFirstReferenceChild(recycler, state) : + findLastReferenceChild(recycler, state); + } + + /** + * Among the children that are suitable to be considered as an anchor child, returns the one + * closest to the start of the layout. + *

+ * Due to ambiguous adapter updates or children being removed, some children's positions may be + * invalid. This method is a best effort to find a position within adapter bounds if possible. + *

+ * It also prioritizes children that are within the visible bounds. + * + * @return A View that can be used an an anchor View. + */ + private View findReferenceChildClosestToStart(RecyclerView.Recycler recycler, + RecyclerView.State state) { + return mShouldReverseLayout ? findLastReferenceChild(recycler, state) : + findFirstReferenceChild(recycler, state); + } + + private View findFirstReferenceChild(RecyclerView.Recycler recycler, RecyclerView.State state) { + return findReferenceChild(recycler, state, 0, getChildCount(), state.getItemCount()); + } + + private View findLastReferenceChild(RecyclerView.Recycler recycler, RecyclerView.State state) { + return findReferenceChild(recycler, state, getChildCount() - 1, -1, state.getItemCount()); + } + + // overridden by GridLayoutManager + View findReferenceChild(RecyclerView.Recycler recycler, RecyclerView.State state, + int start, int end, int itemCount) { + ensureLayoutState(); + View invalidMatch = null; + View outOfBoundsMatch = null; + final int boundsStart = mOrientationHelper.getStartAfterPadding(); + final int boundsEnd = mOrientationHelper.getEndAfterPadding(); + final int diff = end > start ? 1 : -1; + for (int i = start; i != end; i += diff) { + final View view = getChildAt(i); + final int position = getPosition(view); + if (position >= 0 && position < itemCount) { + if (((RecyclerView.LayoutParams) view.getLayoutParams()).isItemRemoved()) { + if (invalidMatch == null) { + invalidMatch = view; // removed item, least preferred + } + } else if (mOrientationHelper.getDecoratedStart(view) >= boundsEnd + || mOrientationHelper.getDecoratedEnd(view) < boundsStart) { + if (outOfBoundsMatch == null) { + outOfBoundsMatch = view; // item is not visible, less preferred + } + } else { + return view; + } + } + } + return outOfBoundsMatch != null ? outOfBoundsMatch : invalidMatch; + } + + // returns the out-of-bound child view closest to RV's end bounds. An out-of-bound child is + // defined as a child that's either partially or fully invisible (outside RV's padding area). + private View findPartiallyOrCompletelyInvisibleChildClosestToEnd() { + return mShouldReverseLayout ? findFirstPartiallyOrCompletelyInvisibleChild() + : findLastPartiallyOrCompletelyInvisibleChild(); + } + + // returns the out-of-bound child view closest to RV's starting bounds. An out-of-bound child is + // defined as a child that's either partially or fully invisible (outside RV's padding area). + private View findPartiallyOrCompletelyInvisibleChildClosestToStart() { + return mShouldReverseLayout ? findLastPartiallyOrCompletelyInvisibleChild() : + findFirstPartiallyOrCompletelyInvisibleChild(); + } + + private View findFirstPartiallyOrCompletelyInvisibleChild() { + return findOnePartiallyOrCompletelyInvisibleChild(0, getChildCount()); + } + + private View findLastPartiallyOrCompletelyInvisibleChild() { + return findOnePartiallyOrCompletelyInvisibleChild(getChildCount() - 1, -1); + } + + /** + * Returns the adapter position of the first visible view. This position does not include + * adapter changes that were dispatched after the last layout pass. + *

+ * Note that, this value is not affected by layout orientation or item order traversal. + * ({@link #setReverseLayout(boolean)}). Views are sorted by their positions in the adapter, + * not in the layout. + *

+ * If RecyclerView has item decorators, they will be considered in calculations as well. + *

+ * LayoutManager may pre-cache some views that are not necessarily visible. Those views + * are ignored in this method. + * + * @return The adapter position of the first visible item or {@link RecyclerView#NO_POSITION} if + * there aren't any visible items. + * @see #findFirstCompletelyVisibleItemPosition() + * @see #findLastVisibleItemPosition() + */ + public int findFirstVisibleItemPosition() { + final View child = findOneVisibleChild(0, getChildCount(), false, true); + return child == null ? RecyclerView.NO_POSITION : getPosition(child); + } + + /** + * Returns the adapter position of the first fully visible view. This position does not include + * adapter changes that were dispatched after the last layout pass. + *

+ * Note that bounds check is only performed in the current orientation. That means, if + * LayoutManager is horizontal, it will only check the view's left and right edges. + * + * @return The adapter position of the first fully visible item or + * {@link RecyclerView#NO_POSITION} if there aren't any visible items. + * @see #findFirstVisibleItemPosition() + * @see #findLastCompletelyVisibleItemPosition() + */ + public int findFirstCompletelyVisibleItemPosition() { + final View child = findOneVisibleChild(0, getChildCount(), true, false); + return child == null ? RecyclerView.NO_POSITION : getPosition(child); + } + + /** + * Returns the adapter position of the last visible view. This position does not include + * adapter changes that were dispatched after the last layout pass. + *

+ * Note that, this value is not affected by layout orientation or item order traversal. + * ({@link #setReverseLayout(boolean)}). Views are sorted by their positions in the adapter, + * not in the layout. + *

+ * If RecyclerView has item decorators, they will be considered in calculations as well. + *

+ * LayoutManager may pre-cache some views that are not necessarily visible. Those views + * are ignored in this method. + * + * @return The adapter position of the last visible view or {@link RecyclerView#NO_POSITION} if + * there aren't any visible items. + * @see #findLastCompletelyVisibleItemPosition() + * @see #findFirstVisibleItemPosition() + */ + public int findLastVisibleItemPosition() { + final View child = findOneVisibleChild(getChildCount() - 1, -1, false, true); + return child == null ? RecyclerView.NO_POSITION : getPosition(child); + } + + /** + * Returns the adapter position of the last fully visible view. This position does not include + * adapter changes that were dispatched after the last layout pass. + *

+ * Note that bounds check is only performed in the current orientation. That means, if + * LayoutManager is horizontal, it will only check the view's left and right edges. + * + * @return The adapter position of the last fully visible view or + * {@link RecyclerView#NO_POSITION} if there aren't any visible items. + * @see #findLastVisibleItemPosition() + * @see #findFirstCompletelyVisibleItemPosition() + */ + public int findLastCompletelyVisibleItemPosition() { + final View child = findOneVisibleChild(getChildCount() - 1, -1, true, false); + return child == null ? RecyclerView.NO_POSITION : getPosition(child); + } + + // Returns the first child that is visible in the provided index range, i.e. either partially or + // fully visible depending on the arguments provided. Completely invisible children are not + // acceptable by this method, but could be returned + // using #findOnePartiallyOrCompletelyInvisibleChild + View findOneVisibleChild(int fromIndex, int toIndex, boolean completelyVisible, + boolean acceptPartiallyVisible) { + ensureLayoutState(); + @ViewBoundsCheck.ViewBounds int preferredBoundsFlag = 0; + @ViewBoundsCheck.ViewBounds int acceptableBoundsFlag = 0; + if (completelyVisible) { + preferredBoundsFlag = (ViewBoundsCheck.FLAG_CVS_GT_PVS | ViewBoundsCheck.FLAG_CVS_EQ_PVS + | ViewBoundsCheck.FLAG_CVE_LT_PVE | ViewBoundsCheck.FLAG_CVE_EQ_PVE); + } else { + preferredBoundsFlag = (ViewBoundsCheck.FLAG_CVS_LT_PVE + | ViewBoundsCheck.FLAG_CVE_GT_PVS); + } + if (acceptPartiallyVisible) { + acceptableBoundsFlag = (ViewBoundsCheck.FLAG_CVS_LT_PVE + | ViewBoundsCheck.FLAG_CVE_GT_PVS); + } + return (mOrientation == HORIZONTAL) ? mHorizontalBoundCheck + .findOneViewWithinBoundFlags(fromIndex, toIndex, preferredBoundsFlag, + acceptableBoundsFlag) : mVerticalBoundCheck + .findOneViewWithinBoundFlags(fromIndex, toIndex, preferredBoundsFlag, + acceptableBoundsFlag); + } + + View findOnePartiallyOrCompletelyInvisibleChild(int fromIndex, int toIndex) { + ensureLayoutState(); + final int next = toIndex > fromIndex ? 1 : (toIndex < fromIndex ? -1 : 0); + if (next == 0) { + return getChildAt(fromIndex); + } + @ViewBoundsCheck.ViewBounds int preferredBoundsFlag = 0; + @ViewBoundsCheck.ViewBounds int acceptableBoundsFlag = 0; + if (mOrientationHelper.getDecoratedStart(getChildAt(fromIndex)) + < mOrientationHelper.getStartAfterPadding()) { + preferredBoundsFlag = (ViewBoundsCheck.FLAG_CVS_LT_PVS | ViewBoundsCheck.FLAG_CVE_LT_PVE + | ViewBoundsCheck.FLAG_CVE_GT_PVS); + acceptableBoundsFlag = (ViewBoundsCheck.FLAG_CVS_LT_PVS + | ViewBoundsCheck.FLAG_CVE_LT_PVE); + } else { + preferredBoundsFlag = (ViewBoundsCheck.FLAG_CVE_GT_PVE | ViewBoundsCheck.FLAG_CVS_GT_PVS + | ViewBoundsCheck.FLAG_CVS_LT_PVE); + acceptableBoundsFlag = (ViewBoundsCheck.FLAG_CVE_GT_PVE + | ViewBoundsCheck.FLAG_CVS_GT_PVS); + } + return (mOrientation == HORIZONTAL) ? mHorizontalBoundCheck + .findOneViewWithinBoundFlags(fromIndex, toIndex, preferredBoundsFlag, + acceptableBoundsFlag) : mVerticalBoundCheck + .findOneViewWithinBoundFlags(fromIndex, toIndex, preferredBoundsFlag, + acceptableBoundsFlag); + } + + @Override + public View onFocusSearchFailed(View focused, int focusDirection, + RecyclerView.Recycler recycler, RecyclerView.State state) { + resolveShouldLayoutReverse(); + if (getChildCount() == 0) { + return null; + } + + final int layoutDir = convertFocusDirectionToLayoutDirection(focusDirection); + if (layoutDir == LayoutState.INVALID_LAYOUT) { + return null; + } + ensureLayoutState(); + final int maxScroll = (int) (MAX_SCROLL_FACTOR * mOrientationHelper.getTotalSpace()); + updateLayoutState(layoutDir, maxScroll, false, state); + mLayoutState.mScrollingOffset = LayoutState.SCROLLING_OFFSET_NaN; + mLayoutState.mRecycle = false; + fill(recycler, mLayoutState, state, true); + + // nextCandidate is the first child view in the layout direction that's partially + // within RV's bounds, i.e. part of it is visible or it's completely invisible but still + // touching RV's bounds. This will be the unfocusable candidate view to become visible onto + // the screen if no focusable views are found in the given layout direction. + final View nextCandidate; + if (layoutDir == LayoutState.LAYOUT_START) { + nextCandidate = findPartiallyOrCompletelyInvisibleChildClosestToStart(); + } else { + nextCandidate = findPartiallyOrCompletelyInvisibleChildClosestToEnd(); + } + // nextFocus is meaningful only if it refers to a focusable child, in which case it + // indicates the next view to gain focus. + final View nextFocus; + if (layoutDir == LayoutState.LAYOUT_START) { + nextFocus = getChildClosestToStart(); + } else { + nextFocus = getChildClosestToEnd(); + } + if (nextFocus.hasFocusable()) { + if (nextCandidate == null) { + return null; + } + return nextFocus; + } + return nextCandidate; + } + + /** + * Used for debugging. + * Logs the internal representation of children to default logger. + */ + private void logChildren() { + Log.d(TAG, "internal representation of views on the screen"); + for (int i = 0; i < getChildCount(); i++) { + View child = getChildAt(i); + Log.d(TAG, "item " + getPosition(child) + ", coord:" + + mOrientationHelper.getDecoratedStart(child)); + } + Log.d(TAG, "=============="); + } + + /** + * Used for debugging. + * Validates that child views are laid out in correct order. This is important because rest of + * the algorithm relies on this constraint. + * + * In default layout, child 0 should be closest to screen position 0 and last child should be + * closest to position WIDTH or HEIGHT. + * In reverse layout, last child should be closes to screen position 0 and first child should + * be closest to position WIDTH or HEIGHT + */ + void validateChildOrder() { + Log.d(TAG, "validating child count " + getChildCount()); + if (getChildCount() < 1) { + return; + } + int lastPos = getPosition(getChildAt(0)); + int lastScreenLoc = mOrientationHelper.getDecoratedStart(getChildAt(0)); + if (mShouldReverseLayout) { + for (int i = 1; i < getChildCount(); i++) { + View child = getChildAt(i); + int pos = getPosition(child); + int screenLoc = mOrientationHelper.getDecoratedStart(child); + if (pos < lastPos) { + logChildren(); + throw new RuntimeException("detected invalid position. loc invalid? " + + (screenLoc < lastScreenLoc)); + } + if (screenLoc > lastScreenLoc) { + logChildren(); + throw new RuntimeException("detected invalid location"); + } + } + } else { + for (int i = 1; i < getChildCount(); i++) { + View child = getChildAt(i); + int pos = getPosition(child); + int screenLoc = mOrientationHelper.getDecoratedStart(child); + if (pos < lastPos) { + logChildren(); + throw new RuntimeException("detected invalid position. loc invalid? " + + (screenLoc < lastScreenLoc)); + } + if (screenLoc < lastScreenLoc) { + logChildren(); + throw new RuntimeException("detected invalid location"); + } + } + } + } + + @Override + public boolean supportsPredictiveItemAnimations() { + return mPendingSavedState == null && mLastStackFromEnd == mStackFromEnd; + } + + /** + * {@inheritDoc} + */ + // This method is only intended to be called (and should only ever be called) by + // ItemTouchHelper. + @Override + public void prepareForDrop(@NonNull View view, @NonNull View target, int x, int y) { + assertNotInLayoutOrScroll("Cannot drop a view during a scroll or layout calculation"); + ensureLayoutState(); + resolveShouldLayoutReverse(); + final int myPos = getPosition(view); + final int targetPos = getPosition(target); + final int dropDirection = myPos < targetPos ? LayoutState.ITEM_DIRECTION_TAIL + : LayoutState.ITEM_DIRECTION_HEAD; + if (mShouldReverseLayout) { + if (dropDirection == LayoutState.ITEM_DIRECTION_TAIL) { + scrollToPositionWithOffset(targetPos, + mOrientationHelper.getEndAfterPadding() + - (mOrientationHelper.getDecoratedStart(target) + + mOrientationHelper.getDecoratedMeasurement(view))); + } else { + scrollToPositionWithOffset(targetPos, + mOrientationHelper.getEndAfterPadding() + - mOrientationHelper.getDecoratedEnd(target)); + } + } else { + if (dropDirection == LayoutState.ITEM_DIRECTION_HEAD) { + scrollToPositionWithOffset(targetPos, mOrientationHelper.getDecoratedStart(target)); + } else { + scrollToPositionWithOffset(targetPos, + mOrientationHelper.getDecoratedEnd(target) + - mOrientationHelper.getDecoratedMeasurement(view)); + } + } + } + + /** + * Helper class that keeps temporary state while {LayoutManager} is filling out the empty + * space. + */ + static class LayoutState { + + static final String TAG = "LLM#LayoutState"; + + static final int LAYOUT_START = -1; + + static final int LAYOUT_END = 1; + + static final int INVALID_LAYOUT = Integer.MIN_VALUE; + + static final int ITEM_DIRECTION_HEAD = -1; + + static final int ITEM_DIRECTION_TAIL = 1; + + static final int SCROLLING_OFFSET_NaN = Integer.MIN_VALUE; + + /** + * We may not want to recycle children in some cases (e.g. layout) + */ + boolean mRecycle = true; + + /** + * Pixel offset where layout should start + */ + int mOffset; + + /** + * Number of pixels that we should fill, in the layout direction. + */ + int mAvailable; + + /** + * Current position on the adapter to get the next item. + */ + int mCurrentPosition; + + /** + * Defines the direction in which the data adapter is traversed. + * Should be {@link #ITEM_DIRECTION_HEAD} or {@link #ITEM_DIRECTION_TAIL} + */ + int mItemDirection; + + /** + * Defines the direction in which the layout is filled. + * Should be {@link #LAYOUT_START} or {@link #LAYOUT_END} + */ + int mLayoutDirection; + + /** + * Used when LayoutState is constructed in a scrolling state. + * It should be set the amount of scrolling we can make without creating a new view. + * Settings this is required for efficient view recycling. + */ + int mScrollingOffset; + + /** + * Used if you want to pre-layout items that are not yet visible. + * The difference with {@link #mAvailable} is that, when recycling, distance laid out for + * {@link #mExtraFillSpace} is not considered to avoid recycling visible children. + */ + int mExtraFillSpace = 0; + + /** + * Contains the {@link #calculateExtraLayoutSpace(RecyclerView.State, int[])} extra layout + * space} that should be excluded for recycling when cleaning up the tail of the list during + * a smooth scroll. + */ + int mNoRecycleSpace = 0; + + /** + * Equal to {@link RecyclerView.State#isPreLayout()}. When consuming scrap, if this value + * is set to true, we skip removed views since they should not be laid out in post layout + * step. + */ + boolean mIsPreLayout = false; + + /** + * The most recent {@link #scrollBy(int, RecyclerView.Recycler, RecyclerView.State)} + * amount. + */ + int mLastScrollDelta; + + /** + * When LLM needs to layout particular views, it sets this list in which case, LayoutState + * will only return views from this list and return null if it cannot find an item. + */ + List mScrapList = null; + + /** + * Used when there is no limit in how many views can be laid out. + */ + boolean mInfinite; + + /** + * @return true if there are more items in the data adapter + */ + boolean hasMore(RecyclerView.State state) { + return mCurrentPosition >= 0 && mCurrentPosition < state.getItemCount(); + } + + /** + * Gets the view for the next element that we should layout. + * Also updates current item index to the next item, based on {@link #mItemDirection} + * + * @return The next element that we should layout. + */ + View next(RecyclerView.Recycler recycler) { + if (mScrapList != null) { + return nextViewFromScrapList(); + } + final View view = recycler.getViewForPosition(mCurrentPosition); + mCurrentPosition += mItemDirection; + return view; + } + + /** + * Returns the next item from the scrap list. + *

+ * Upon finding a valid VH, sets current item position to VH.itemPosition + mItemDirection + * + * @return View if an item in the current position or direction exists if not null. + */ + private View nextViewFromScrapList() { + final int size = mScrapList.size(); + for (int i = 0; i < size; i++) { + final View view = mScrapList.get(i).itemView; + final RecyclerView.LayoutParams lp = (RecyclerView.LayoutParams) view.getLayoutParams(); + if (lp.isItemRemoved()) { + continue; + } + if (mCurrentPosition == lp.getViewLayoutPosition()) { + assignPositionFromScrapList(view); + return view; + } + } + return null; + } + + public void assignPositionFromScrapList() { + assignPositionFromScrapList(null); + } + + public void assignPositionFromScrapList(View ignore) { + final View closest = nextViewInLimitedList(ignore); + if (closest == null) { + mCurrentPosition = RecyclerView.NO_POSITION; + } else { + mCurrentPosition = ((RecyclerView.LayoutParams) closest.getLayoutParams()) + .getViewLayoutPosition(); + } + } + + public View nextViewInLimitedList(View ignore) { + int size = mScrapList.size(); + View closest = null; + int closestDistance = Integer.MAX_VALUE; + if (DEBUG && mIsPreLayout) { + throw new IllegalStateException("Scrap list cannot be used in pre layout"); + } + for (int i = 0; i < size; i++) { + View view = mScrapList.get(i).itemView; + final RecyclerView.LayoutParams lp = (RecyclerView.LayoutParams) view.getLayoutParams(); + if (view == ignore || lp.isItemRemoved()) { + continue; + } + final int distance = (lp.getViewLayoutPosition() - mCurrentPosition) + * mItemDirection; + if (distance < 0) { + continue; // item is not in current direction + } + if (distance < closestDistance) { + closest = view; + closestDistance = distance; + if (distance == 0) { + break; + } + } + } + return closest; + } + + void log() { + Log.d(TAG, "avail:" + mAvailable + ", ind:" + mCurrentPosition + ", dir:" + + mItemDirection + ", offset:" + mOffset + ", layoutDir:" + mLayoutDirection); + } + } + + /** + * @hide + */ + @RestrictTo(LIBRARY) + @SuppressLint("BanParcelableUsage") + public static class SavedState implements Parcelable { + + int mAnchorPosition; + + int mAnchorOffset; + + boolean mAnchorLayoutFromEnd; + + public SavedState() { + + } + + SavedState(Parcel in) { + mAnchorPosition = in.readInt(); + mAnchorOffset = in.readInt(); + mAnchorLayoutFromEnd = in.readInt() == 1; + } + + public SavedState(SavedState other) { + mAnchorPosition = other.mAnchorPosition; + mAnchorOffset = other.mAnchorOffset; + mAnchorLayoutFromEnd = other.mAnchorLayoutFromEnd; + } + + boolean hasValidAnchor() { + return mAnchorPosition >= 0; + } + + void invalidateAnchor() { + mAnchorPosition = RecyclerView.NO_POSITION; + } + + @Override + public int describeContents() { + return 0; + } + + @Override + public void writeToParcel(Parcel dest, int flags) { + dest.writeInt(mAnchorPosition); + dest.writeInt(mAnchorOffset); + dest.writeInt(mAnchorLayoutFromEnd ? 1 : 0); + } + + public static final Parcelable.Creator CREATOR = + new Parcelable.Creator() { + @Override + public SavedState createFromParcel(Parcel in) { + return new SavedState(in); + } + + @Override + public SavedState[] newArray(int size) { + return new SavedState[size]; + } + }; + } + + /** + * Simple data class to keep Anchor information + */ + static class AnchorInfo { + OrientationHelper mOrientationHelper; + int mPosition; + int mCoordinate; + boolean mLayoutFromEnd; + boolean mValid; + + AnchorInfo() { + reset(); + } + + void reset() { + mPosition = RecyclerView.NO_POSITION; + mCoordinate = INVALID_OFFSET; + mLayoutFromEnd = false; + mValid = false; + } + + /** + * assigns anchor coordinate from the RecyclerView's padding depending on current + * layoutFromEnd value + */ + void assignCoordinateFromPadding() { + mCoordinate = mLayoutFromEnd + ? mOrientationHelper.getEndAfterPadding() + : mOrientationHelper.getStartAfterPadding(); + } + + @Override + public String toString() { + return "AnchorInfo{" + + "mPosition=" + mPosition + + ", mCoordinate=" + mCoordinate + + ", mLayoutFromEnd=" + mLayoutFromEnd + + ", mValid=" + mValid + + '}'; + } + + boolean isViewValidAsAnchor(View child, RecyclerView.State state) { + RecyclerView.LayoutParams lp = (RecyclerView.LayoutParams) child.getLayoutParams(); + return !lp.isItemRemoved() && lp.getViewLayoutPosition() >= 0 + && lp.getViewLayoutPosition() < state.getItemCount(); + } + + public void assignFromViewAndKeepVisibleRect(View child, int position) { + final int spaceChange = mOrientationHelper.getTotalSpaceChange(); + if (spaceChange >= 0) { + assignFromView(child, position); + return; + } + mPosition = position; + if (mLayoutFromEnd) { + final int prevLayoutEnd = mOrientationHelper.getEndAfterPadding() - spaceChange; + final int childEnd = mOrientationHelper.getDecoratedEnd(child); + final int previousEndMargin = prevLayoutEnd - childEnd; + mCoordinate = mOrientationHelper.getEndAfterPadding() - previousEndMargin; + // ensure we did not push child's top out of bounds because of this + if (previousEndMargin > 0) { // we have room to shift bottom if necessary + final int childSize = mOrientationHelper.getDecoratedMeasurement(child); + final int estimatedChildStart = mCoordinate - childSize; + final int layoutStart = mOrientationHelper.getStartAfterPadding(); + final int previousStartMargin = mOrientationHelper.getDecoratedStart(child) + - layoutStart; + final int startReference = layoutStart + Math.min(previousStartMargin, 0); + final int startMargin = estimatedChildStart - startReference; + if (startMargin < 0) { + // offset to make top visible but not too much + mCoordinate += Math.min(previousEndMargin, -startMargin); + } + } + } else { + final int childStart = mOrientationHelper.getDecoratedStart(child); + final int startMargin = childStart - mOrientationHelper.getStartAfterPadding(); + mCoordinate = childStart; + if (startMargin > 0) { // we have room to fix end as well + final int estimatedEnd = childStart + + mOrientationHelper.getDecoratedMeasurement(child); + final int previousLayoutEnd = mOrientationHelper.getEndAfterPadding() + - spaceChange; + final int previousEndMargin = previousLayoutEnd + - mOrientationHelper.getDecoratedEnd(child); + final int endReference = mOrientationHelper.getEndAfterPadding() + - Math.min(0, previousEndMargin); + final int endMargin = endReference - estimatedEnd; + if (endMargin < 0) { + mCoordinate -= Math.min(startMargin, -endMargin); + } + } + } + } + + public void assignFromView(View child, int position) { + if (mLayoutFromEnd) { + mCoordinate = mOrientationHelper.getDecoratedEnd(child) + + mOrientationHelper.getTotalSpaceChange(); + } else { + mCoordinate = mOrientationHelper.getDecoratedStart(child); + } + + mPosition = position; + } + } + + protected static class LayoutChunkResult { + public int mConsumed; + public boolean mFinished; + public boolean mIgnoreConsumed; + public boolean mFocusable; + + void resetInternal() { + mConsumed = 0; + mFinished = false; + mIgnoreConsumed = false; + mFocusable = false; + } + } +} diff --git a/viewpager2/src/main/java/com/vinsonguo/viewpager2/adapter/FragmentStateAdapter.java b/viewpager2/src/main/java/com/vinsonguo/viewpager2/adapter/FragmentStateAdapter.java new file mode 100644 index 0000000..8efdddf --- /dev/null +++ b/viewpager2/src/main/java/com/vinsonguo/viewpager2/adapter/FragmentStateAdapter.java @@ -0,0 +1,777 @@ +package com.vinsonguo.viewpager2.adapter; +/* + * Copyright 2018 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +import static android.arch.lifecycle.Lifecycle.State.RESUMED; +import static android.arch.lifecycle.Lifecycle.State.STARTED; +import static android.support.v4.util.Preconditions.checkArgument; +import static android.support.v7.widget.RecyclerView.NO_ID; + +import android.annotation.SuppressLint; +import android.arch.lifecycle.GenericLifecycleObserver; +import android.arch.lifecycle.Lifecycle; +import android.arch.lifecycle.LifecycleOwner; +import android.os.Bundle; +import android.os.Handler; +import android.os.Looper; +import android.os.Parcelable; +import android.support.annotation.CallSuper; +import android.support.annotation.NonNull; +import android.support.annotation.Nullable; +import android.support.v4.app.Fragment; +import android.support.v4.app.FragmentActivity; +import android.support.v4.app.FragmentManager; +import android.support.v4.app.FragmentTransaction; +import android.support.v4.util.ArraySet; +import android.support.v4.util.LongSparseArray; +import android.support.v4.view.ViewCompat; +import android.support.v7.widget.RecyclerView; +import android.view.View; +import android.view.ViewGroup; +import android.view.ViewParent; +import android.widget.FrameLayout; + +import com.vinsonguo.viewpager2.widget.ViewPager2; + +import java.util.Set; + +/** + * Similar in behavior to {@link FragmentStatePagerAdapter} + *

+ * Lifecycle within {@link RecyclerView}: + *

    + *
  • {@link RecyclerView.ViewHolder} initially an empty {@link FrameLayout}, serves as a + * re-usable container for a {@link Fragment} in later stages. + *
  • {@link RecyclerView.Adapter#onBindViewHolder} we ask for a {@link Fragment} for the + * position. If we already have the fragment, or have previously saved its state, we use those. + *
  • {@link RecyclerView.Adapter#onAttachedToWindow} we attach the {@link Fragment} to a + * container. + *
  • {@link RecyclerView.Adapter#onViewRecycled} we remove, save state, destroy the + * {@link Fragment}. + *
+ */ +public abstract class FragmentStateAdapter extends + RecyclerView.Adapter implements StatefulAdapter { + // State saving config + private static final String KEY_PREFIX_FRAGMENT = "f#"; + private static final String KEY_PREFIX_STATE = "s#"; + + // Fragment GC config + private static final long GRACE_WINDOW_TIME_MS = 10_000; // 10 seconds + + @SuppressWarnings("WeakerAccess") // to avoid creation of a synthetic accessor + final Lifecycle mLifecycle; + @SuppressWarnings("WeakerAccess") // to avoid creation of a synthetic accessor + final FragmentManager mFragmentManager; + + // Fragment bookkeeping + @SuppressWarnings("WeakerAccess") // to avoid creation of a synthetic accessor + final LongSparseArray mFragments = new LongSparseArray<>(); + private final LongSparseArray mSavedStates = new LongSparseArray<>(); + private final LongSparseArray mItemIdToViewHolder = new LongSparseArray<>(); + + private FragmentMaxLifecycleEnforcer mFragmentMaxLifecycleEnforcer; + + // Fragment GC + @SuppressWarnings("WeakerAccess") // to avoid creation of a synthetic accessor + boolean mIsInGracePeriod = false; + private boolean mHasStaleFragments = false; + + /** + * @param fragmentActivity if the {@link ViewPager2} lives directly in a + * {@link FragmentActivity} subclass. + * + * @see FragmentStateAdapter#FragmentStateAdapter(Fragment) + * @see FragmentStateAdapter#FragmentStateAdapter(FragmentManager, Lifecycle) + */ + public FragmentStateAdapter(@NonNull FragmentActivity fragmentActivity) { + this(fragmentActivity.getSupportFragmentManager(), fragmentActivity.getLifecycle()); + } + + /** + * @param fragment if the {@link ViewPager2} lives directly in a {@link Fragment} subclass. + * + * @see FragmentStateAdapter#FragmentStateAdapter(FragmentActivity) + * @see FragmentStateAdapter#FragmentStateAdapter(FragmentManager, Lifecycle) + */ + public FragmentStateAdapter(@NonNull Fragment fragment) { + this(fragment.getChildFragmentManager(), fragment.getLifecycle()); + } + + /** + * @param fragmentManager of {@link ViewPager2}'s host + * @param lifecycle of {@link ViewPager2}'s host + * + * @see FragmentStateAdapter#FragmentStateAdapter(FragmentActivity) + * @see FragmentStateAdapter#FragmentStateAdapter(Fragment) + */ + public FragmentStateAdapter(@NonNull FragmentManager fragmentManager, + @NonNull Lifecycle lifecycle) { + mFragmentManager = fragmentManager; + mLifecycle = lifecycle; + super.setHasStableIds(true); + } + + @SuppressLint("RestrictedApi") + @CallSuper + @Override + public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) { + checkArgument(mFragmentMaxLifecycleEnforcer == null); + mFragmentMaxLifecycleEnforcer = new FragmentMaxLifecycleEnforcer(); + mFragmentMaxLifecycleEnforcer.register(recyclerView); + } + + @CallSuper + @Override + public void onDetachedFromRecyclerView(@NonNull RecyclerView recyclerView) { + mFragmentMaxLifecycleEnforcer.unregister(recyclerView); + mFragmentMaxLifecycleEnforcer = null; + } + + /** + * Provide a new Fragment associated with the specified position. + *

+ * The adapter will be responsible for the Fragment lifecycle: + *

    + *
  • The Fragment will be used to display an item.
  • + *
  • The Fragment will be destroyed when it gets too far from the viewport, and its state + * will be saved. When the item is close to the viewport again, a new Fragment will be + * requested, and a previously saved state will be used to initialize it. + *
+ * @see ViewPager2#setOffscreenPageLimit + */ + public abstract @NonNull Fragment createFragment(int position); + + @NonNull + @Override + public final FragmentViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { + return FragmentViewHolder.create(parent); + } + + @Override + public final void onBindViewHolder(final @NonNull FragmentViewHolder holder, int position) { + final long itemId = holder.getItemId(); + final int viewHolderId = holder.getContainer().getId(); + final Long boundItemId = itemForViewHolder(viewHolderId); // item currently bound to the VH + if (boundItemId != null && boundItemId != itemId) { + removeFragment(boundItemId); + mItemIdToViewHolder.remove(boundItemId); + } + + mItemIdToViewHolder.put(itemId, viewHolderId); // this might overwrite an existing entry + ensureFragment(position); + + /** Special case when {@link RecyclerView} decides to keep the {@link container} + * attached to the window, but not to the view hierarchy (i.e. parent is null) */ + final FrameLayout container = holder.getContainer(); + if (ViewCompat.isAttachedToWindow(container)) { + if (container.getParent() != null) { + throw new IllegalStateException("Design assumption violated."); + } + container.addOnLayoutChangeListener(new View.OnLayoutChangeListener() { + @Override + public void onLayoutChange(View v, int left, int top, int right, int bottom, + int oldLeft, int oldTop, int oldRight, int oldBottom) { + if (container.getParent() != null) { + container.removeOnLayoutChangeListener(this); + placeFragmentInViewHolder(holder); + } + } + }); + } + + gcFragments(); + } + + @SuppressWarnings("WeakerAccess") // to avoid creation of a synthetic accessor + void gcFragments() { + if (!mHasStaleFragments || shouldDelayFragmentTransactions()) { + return; + } + + // Remove Fragments for items that are no longer part of the data-set + Set toRemove = new ArraySet<>(); + for (int ix = 0; ix < mFragments.size(); ix++) { + long itemId = mFragments.keyAt(ix); + if (!containsItem(itemId)) { + toRemove.add(itemId); + mItemIdToViewHolder.remove(itemId); // in case they're still bound + } + } + + // Remove Fragments that are not bound anywhere -- pending a grace period + if (!mIsInGracePeriod) { + mHasStaleFragments = false; // we've executed all GC checks + + for (int ix = 0; ix < mFragments.size(); ix++) { + long itemId = mFragments.keyAt(ix); + if (!isFragmentViewBound(itemId)) { + toRemove.add(itemId); + } + } + } + + for (Long itemId : toRemove) { + removeFragment(itemId); + } + } + + private boolean isFragmentViewBound(long itemId) { + if (mItemIdToViewHolder.containsKey(itemId)) { + return true; + } + + Fragment fragment = mFragments.get(itemId); + if (fragment == null) { + return false; + } + + View view = fragment.getView(); + if (view == null) { + return false; + } + + return view.getParent() != null; + } + + private Long itemForViewHolder(int viewHolderId) { + Long boundItemId = null; + for (int ix = 0; ix < mItemIdToViewHolder.size(); ix++) { + if (mItemIdToViewHolder.valueAt(ix) == viewHolderId) { + if (boundItemId != null) { + throw new IllegalStateException("Design assumption violated: " + + "a ViewHolder can only be bound to one item at a time."); + } + boundItemId = mItemIdToViewHolder.keyAt(ix); + } + } + return boundItemId; + } + + private void ensureFragment(int position) { + long itemId = getItemId(position); + if (!mFragments.containsKey(itemId)) { + // TODO(133419201): check if a Fragment provided here is a new Fragment + Fragment newFragment = createFragment(position); + newFragment.setInitialSavedState(mSavedStates.get(itemId)); + mFragments.put(itemId, newFragment); + } + } + + @Override + public final void onViewAttachedToWindow(@NonNull final FragmentViewHolder holder) { + placeFragmentInViewHolder(holder); + gcFragments(); + } + + /** + * @param holder that has been bound to a Fragment in the {@link #onBindViewHolder} stage. + */ + @SuppressWarnings("WeakerAccess") // to avoid creation of a synthetic accessor + void placeFragmentInViewHolder(@NonNull final FragmentViewHolder holder) { + Fragment fragment = mFragments.get(holder.getItemId()); + if (fragment == null) { + throw new IllegalStateException("Design assumption violated."); + } + FrameLayout container = holder.getContainer(); + View view = fragment.getView(); + + /* + possible states: + - fragment: { added, notAdded } + - view: { created, notCreated } + - view: { attached, notAttached } + + combinations: + - { f:added, v:created, v:attached } -> check if attached to the right container + - { f:added, v:created, v:notAttached} -> attach view to container + - { f:added, v:notCreated, v:attached } -> impossible + - { f:added, v:notCreated, v:notAttached} -> schedule callback for when created + - { f:notAdded, v:created, v:attached } -> illegal state + - { f:notAdded, v:created, v:notAttached } -> illegal state + - { f:notAdded, v:notCreated, v:attached } -> impossible + - { f:notAdded, v:notCreated, v:notAttached } -> add, create, attach + */ + + // { f:notAdded, v:created, v:attached } -> illegal state + // { f:notAdded, v:created, v:notAttached } -> illegal state + if (!fragment.isAdded() && view != null) { + throw new IllegalStateException("Design assumption violated."); + } + + // { f:added, v:notCreated, v:notAttached} -> schedule callback for when created + if (fragment.isAdded() && view == null) { + scheduleViewAttach(fragment, container); + return; + } + + // { f:added, v:created, v:attached } -> check if attached to the right container + if (fragment.isAdded() && view.getParent() != null) { + if (view.getParent() != container) { + addViewToContainer(view, container); + } + return; + } + + // { f:added, v:created, v:notAttached} -> attach view to container + if (fragment.isAdded()) { + addViewToContainer(view, container); + return; + } + + // { f:notAdded, v:notCreated, v:notAttached } -> add, create, attach + if (!shouldDelayFragmentTransactions()) { + scheduleViewAttach(fragment, container); + mFragmentManager.beginTransaction() + .add(fragment, "f" + holder.getItemId()) +// .setMaxLifecycle(fragment, STARTED) + .commitNow(); + mFragmentMaxLifecycleEnforcer.updateFragmentMaxLifecycle(false); + } else { + if (mFragmentManager.isDestroyed()) { + return; // nothing we can do + } + mLifecycle.addObserver(new GenericLifecycleObserver() { + @Override + public void onStateChanged(@NonNull LifecycleOwner source, + @NonNull Lifecycle.Event event) { + if (shouldDelayFragmentTransactions()) { + return; + } + source.getLifecycle().removeObserver(this); + if (ViewCompat.isAttachedToWindow(holder.getContainer())) { + placeFragmentInViewHolder(holder); + } + } + }); + } + } + + private void scheduleViewAttach(final Fragment fragment, @NonNull final FrameLayout container) { + // After a config change, Fragments that were in FragmentManager will be recreated. Since + // ViewHolder container ids are dynamically generated, we opted to manually handle + // attaching Fragment views to containers. For consistency, we use the same mechanism for + // all Fragment views. + mFragmentManager.registerFragmentLifecycleCallbacks( + new FragmentManager.FragmentLifecycleCallbacks() { + // TODO(b/141956012): Suppressed during upgrade to AGP 3.6. + @SuppressWarnings("ReferenceEquality") + @Override + public void onFragmentViewCreated(@NonNull FragmentManager fm, + @NonNull Fragment f, @NonNull View v, + @Nullable Bundle savedInstanceState) { + if (f == fragment) { + fm.unregisterFragmentLifecycleCallbacks(this); + addViewToContainer(v, container); + } + } + }, false); + } + + @SuppressWarnings("WeakerAccess") // to avoid creation of a synthetic accessor + void addViewToContainer(@NonNull View v, @NonNull FrameLayout container) { + if (container.getChildCount() > 1) { + throw new IllegalStateException("Design assumption violated."); + } + + if (v.getParent() == container) { + return; + } + + if (container.getChildCount() > 0) { + container.removeAllViews(); + } + + if (v.getParent() != null) { + ((ViewGroup) v.getParent()).removeView(v); + } + + container.addView(v); + } + + @Override + public final void onViewRecycled(@NonNull FragmentViewHolder holder) { + final int viewHolderId = holder.getContainer().getId(); + final Long boundItemId = itemForViewHolder(viewHolderId); // item currently bound to the VH + if (boundItemId != null) { + removeFragment(boundItemId); + mItemIdToViewHolder.remove(boundItemId); + } + } + + @Override + public final boolean onFailedToRecycleView(@NonNull FragmentViewHolder holder) { + /* + This happens when a ViewHolder is in a transient state (e.g. during an + animation). + + Our ViewHolders are effectively just FrameLayout instances in which we put Fragment + Views, so it's safe to force recycle them. This is because: + - FrameLayout instances are not to be directly manipulated, so no animations are + expected to be running directly on them. + - Fragment Views are not reused between position (one Fragment = one page). Animation + running in one of the Fragment Views won't affect another Fragment View. + - If a user chooses to violate these assumptions, they are also in the position to + correct the state in their code. + */ + return true; + } + + private void removeFragment(long itemId) { + Fragment fragment = mFragments.get(itemId); + + if (fragment == null) { + return; + } + + if (fragment.getView() != null) { + ViewParent viewParent = fragment.getView().getParent(); + if (viewParent != null) { + ((FrameLayout) viewParent).removeAllViews(); + } + } + + if (!containsItem(itemId)) { + mSavedStates.remove(itemId); + } + + if (!fragment.isAdded()) { + mFragments.remove(itemId); + return; + } + + if (shouldDelayFragmentTransactions()) { + mHasStaleFragments = true; + return; + } + + if (fragment.isAdded() && containsItem(itemId)) { + mSavedStates.put(itemId, mFragmentManager.saveFragmentInstanceState(fragment)); + } + mFragmentManager.beginTransaction().remove(fragment).commitNow(); + mFragments.remove(itemId); + } + + @SuppressWarnings("WeakerAccess") // to avoid creation of a synthetic accessor + boolean shouldDelayFragmentTransactions() { + return mFragmentManager.isStateSaved(); + } + + /** + * Default implementation works for collections that don't add, move, remove items. + *

+ * TODO(b/122670460): add lint rule + * When overriding, also override {@link #containsItem(long)}. + *

+ * If the item is not a part of the collection, return {@link RecyclerView#NO_ID}. + * + * @param position Adapter position + * @return stable item id {@link RecyclerView.Adapter#hasStableIds()} + */ + @Override + public long getItemId(int position) { + return position; + } + + /** + * Default implementation works for collections that don't add, move, remove items. + *

+ * TODO(b/122670460): add lint rule + * When overriding, also override {@link #getItemId(int)} + */ + public boolean containsItem(long itemId) { + return itemId >= 0 && itemId < getItemCount(); + } + + @Override + public final void setHasStableIds(boolean hasStableIds) { + throw new UnsupportedOperationException( + "Stable Ids are required for the adapter to function properly, and the adapter " + + "takes care of setting the flag."); + } + + @Override + public final @NonNull Parcelable saveState() { + /** TODO(b/122670461): use custom {@link Parcelable} instead of Bundle to save space */ + Bundle savedState = new Bundle(mFragments.size() + mSavedStates.size()); + + /** save references to active fragments */ + for (int ix = 0; ix < mFragments.size(); ix++) { + long itemId = mFragments.keyAt(ix); + Fragment fragment = mFragments.get(itemId); + if (fragment != null && fragment.isAdded()) { + String key = createKey(KEY_PREFIX_FRAGMENT, itemId); + mFragmentManager.putFragment(savedState, key, fragment); + } + } + + /** Write {@link mSavedStates) into a {@link Parcelable} */ + for (int ix = 0; ix < mSavedStates.size(); ix++) { + long itemId = mSavedStates.keyAt(ix); + if (containsItem(itemId)) { + String key = createKey(KEY_PREFIX_STATE, itemId); + savedState.putParcelable(key, mSavedStates.get(itemId)); + } + } + + return savedState; + } + + @Override + public final void restoreState(@NonNull Parcelable savedState) { + if (!mSavedStates.isEmpty() || !mFragments.isEmpty()) { + throw new IllegalStateException( + "Expected the adapter to be 'fresh' while restoring state."); + } + + Bundle bundle = (Bundle) savedState; + if (bundle.getClassLoader() == null) { + /** TODO(b/133752041): pass the class loader from {@link ViewPager2.SavedState } */ + bundle.setClassLoader(getClass().getClassLoader()); + } + + for (String key : bundle.keySet()) { + if (isValidKey(key, KEY_PREFIX_FRAGMENT)) { + long itemId = parseIdFromKey(key, KEY_PREFIX_FRAGMENT); + Fragment fragment = mFragmentManager.getFragment(bundle, key); + mFragments.put(itemId, fragment); + continue; + } + + if (isValidKey(key, KEY_PREFIX_STATE)) { + long itemId = parseIdFromKey(key, KEY_PREFIX_STATE); + Fragment.SavedState state = bundle.getParcelable(key); + if (containsItem(itemId)) { + mSavedStates.put(itemId, state); + } + continue; + } + + throw new IllegalArgumentException("Unexpected key in savedState: " + key); + } + + if (!mFragments.isEmpty()) { + mHasStaleFragments = true; + mIsInGracePeriod = true; + gcFragments(); + scheduleGracePeriodEnd(); + } + } + + private void scheduleGracePeriodEnd() { + final Handler handler = new Handler(Looper.getMainLooper()); + final Runnable runnable = new Runnable() { + @Override + public void run() { + mIsInGracePeriod = false; + gcFragments(); // good opportunity to GC + } + }; + + mLifecycle.addObserver(new GenericLifecycleObserver() { + @Override + public void onStateChanged(@NonNull LifecycleOwner source, + @NonNull Lifecycle.Event event) { + if (event == Lifecycle.Event.ON_DESTROY) { + handler.removeCallbacks(runnable); + source.getLifecycle().removeObserver(this); + } + } + }); + + handler.postDelayed(runnable, GRACE_WINDOW_TIME_MS); + } + + // Helper function for dealing with save / restore state + private static @NonNull String createKey(@NonNull String prefix, long id) { + return prefix + id; + } + + // Helper function for dealing with save / restore state + private static boolean isValidKey(@NonNull String key, @NonNull String prefix) { + return key.startsWith(prefix) && key.length() > prefix.length(); + } + + // Helper function for dealing with save / restore state + private static long parseIdFromKey(@NonNull String key, @NonNull String prefix) { + return Long.parseLong(key.substring(prefix.length())); + } + + /** + * Pauses (STARTED) all Fragments that are attached and not a primary item. + * Keeps primary item Fragment RESUMED. + */ + class FragmentMaxLifecycleEnforcer { + private ViewPager2.OnPageChangeCallback mPageChangeCallback; + private RecyclerView.AdapterDataObserver mDataObserver; + private GenericLifecycleObserver mLifecycleObserver; + private ViewPager2 mViewPager; + + private long mPrimaryItemId = NO_ID; + + void register(@NonNull RecyclerView recyclerView) { + mViewPager = inferViewPager(recyclerView); + + // signal 1 of 3: current item has changed + mPageChangeCallback = new ViewPager2.OnPageChangeCallback() { + @Override + public void onPageScrollStateChanged(int state) { + updateFragmentMaxLifecycle(false); + } + + @Override + public void onPageSelected(int position) { + updateFragmentMaxLifecycle(false); + } + }; + mViewPager.registerOnPageChangeCallback(mPageChangeCallback); + + // signal 2 of 3: underlying data-set has been updated + mDataObserver = new DataSetChangeObserver() { + @Override + public void onChanged() { + updateFragmentMaxLifecycle(true); + } + }; + registerAdapterDataObserver(mDataObserver); + + // signal 3 of 3: we may have to catch-up after being in a lifecycle state that + // prevented us to perform transactions + + mLifecycleObserver = new GenericLifecycleObserver() { + @Override + public void onStateChanged(@NonNull LifecycleOwner source, + @NonNull Lifecycle.Event event) { + updateFragmentMaxLifecycle(false); + } + }; + mLifecycle.addObserver(mLifecycleObserver); + } + + void unregister(@NonNull RecyclerView recyclerView) { + ViewPager2 viewPager = inferViewPager(recyclerView); + viewPager.unregisterOnPageChangeCallback(mPageChangeCallback); + unregisterAdapterDataObserver(mDataObserver); + mLifecycle.removeObserver(mLifecycleObserver); + mViewPager = null; + } + + void updateFragmentMaxLifecycle(boolean dataSetChanged) { + if (shouldDelayFragmentTransactions()) { + return; /** recovery step via {@link #mLifecycleObserver} */ + } + + if (mViewPager.getScrollState() != ViewPager2.SCROLL_STATE_IDLE) { + return; // do not update while not idle to avoid jitter + } + + if (mFragments.isEmpty() || getItemCount() == 0) { + return; // nothing to do + } + + final int currentItem = mViewPager.getCurrentItem(); + if (currentItem >= getItemCount()) { + /** current item is yet to be updated; it is guaranteed to change, so we will be + * notified via {@link ViewPager2.OnPageChangeCallback#onPageSelected(int)} */ + return; + } + + long currentItemId = getItemId(currentItem); + if (currentItemId == mPrimaryItemId && !dataSetChanged) { + return; // nothing to do + } + + Fragment currentItemFragment = mFragments.get(currentItemId); + if (currentItemFragment == null || !currentItemFragment.isAdded()) { + return; + } + + mPrimaryItemId = currentItemId; + FragmentTransaction transaction = mFragmentManager.beginTransaction(); + + Fragment toResume = null; + for (int ix = 0; ix < mFragments.size(); ix++) { + long itemId = mFragments.keyAt(ix); + Fragment fragment = mFragments.valueAt(ix); + + if (!fragment.isAdded()) { + continue; + } + + if (itemId != mPrimaryItemId) { +// transaction.setMaxLifecycle(fragment, STARTED); + } else { + toResume = fragment; // itemId map key, so only one can match the predicate + } + + fragment.setMenuVisibility(itemId == mPrimaryItemId); + } + if (toResume != null) { // in case the Fragment wasn't added yet +// transaction.setMaxLifecycle(toResume, RESUMED); + } + + if (!transaction.isEmpty()) { + transaction.commitNow(); + } + } + + @NonNull + private ViewPager2 inferViewPager(@NonNull RecyclerView recyclerView) { + ViewParent parent = recyclerView.getParent(); + if (parent instanceof ViewPager2) { + return (ViewPager2) parent; + } + throw new IllegalStateException("Expected ViewPager2 instance. Got: " + parent); + } + } + + /** + * Simplified {@link RecyclerView.AdapterDataObserver} for clients interested in any data-set + * changes regardless of their nature. + */ + private abstract static class DataSetChangeObserver extends RecyclerView.AdapterDataObserver { + @Override + public abstract void onChanged(); + + @Override + public final void onItemRangeChanged(int positionStart, int itemCount) { + onChanged(); + } + + @Override + public final void onItemRangeChanged(int positionStart, int itemCount, + @Nullable Object payload) { + onChanged(); + } + + @Override + public final void onItemRangeInserted(int positionStart, int itemCount) { + onChanged(); + } + + @Override + public final void onItemRangeRemoved(int positionStart, int itemCount) { + onChanged(); + } + + @Override + public final void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) { + onChanged(); + } + } +} diff --git a/viewpager2/src/main/java/com/vinsonguo/viewpager2/adapter/FragmentViewHolder.java b/viewpager2/src/main/java/com/vinsonguo/viewpager2/adapter/FragmentViewHolder.java new file mode 100644 index 0000000..0aae372 --- /dev/null +++ b/viewpager2/src/main/java/com/vinsonguo/viewpager2/adapter/FragmentViewHolder.java @@ -0,0 +1,30 @@ +package com.vinsonguo.viewpager2.adapter; + +import android.support.annotation.NonNull; +import android.support.v4.view.ViewCompat; +import android.support.v7.widget.RecyclerView; +import android.view.ViewGroup; +import android.widget.FrameLayout; +/** + * {@link ViewHolder} implementation for handling {@link Fragment}s. Used in + * {@link FragmentStateAdapter}. + */ +public final class FragmentViewHolder extends RecyclerView.ViewHolder { + private FragmentViewHolder(@NonNull FrameLayout container) { + super(container); + } + + @NonNull static FragmentViewHolder create(@NonNull ViewGroup parent) { + FrameLayout container = new FrameLayout(parent.getContext()); + container.setLayoutParams( + new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, + ViewGroup.LayoutParams.MATCH_PARENT)); + container.setId(ViewCompat.generateViewId()); + container.setSaveEnabled(false); + return new FragmentViewHolder(container); + } + + @NonNull FrameLayout getContainer() { + return (FrameLayout) itemView; + } +} diff --git a/viewpager2/src/main/java/com/vinsonguo/viewpager2/adapter/StatefulAdapter.java b/viewpager2/src/main/java/com/vinsonguo/viewpager2/adapter/StatefulAdapter.java new file mode 100644 index 0000000..c12ad72 --- /dev/null +++ b/viewpager2/src/main/java/com/vinsonguo/viewpager2/adapter/StatefulAdapter.java @@ -0,0 +1,18 @@ +package com.vinsonguo.viewpager2.adapter; +import android.os.Parcelable; +import android.support.annotation.NonNull; +import android.view.View; + + +/** + * {@link ViewPager2} adapters should implement this interface to be called during + * {@link View#onSaveInstanceState()} and {@link View#onRestoreInstanceState(Parcelable)} + */ +public interface StatefulAdapter { + /** Saves adapter state */ + @NonNull + Parcelable saveState(); + + /** Restores adapter state */ + void restoreState(@NonNull Parcelable savedState); +} diff --git a/viewpager2/src/main/java/com/vinsonguo/viewpager2/widget/AnimateLayoutChangeDetector.java b/viewpager2/src/main/java/com/vinsonguo/viewpager2/widget/AnimateLayoutChangeDetector.java new file mode 100644 index 0000000..e280ffe --- /dev/null +++ b/viewpager2/src/main/java/com/vinsonguo/viewpager2/widget/AnimateLayoutChangeDetector.java @@ -0,0 +1,125 @@ +package com.vinsonguo.viewpager2.widget; +import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; +import static com.vinsonguo.viewpager2.widget.ViewPager2.ORIENTATION_HORIZONTAL; + +import android.animation.LayoutTransition; +import android.support.annotation.NonNull; +import android.support.v7.widget.LinearLayoutManager; +import android.support.v7.widget.ViewPager2LinearLayoutManager; +import android.view.View; +import android.view.ViewGroup; + + +import java.util.Arrays; +import java.util.Comparator; + +/** + * Class used to detect if there are gaps between pages and if any of the pages contain a running + * change-transition in case we detected an illegal state in the {@link ScrollEventAdapter}. + * + * This is an approximation of the detection and could potentially lead to misleading advice. If we + * hit problems with it, remove the detection and replace with a suggestive error message instead, + * like "Negative page offset encountered. Did you setAnimateParentHierarchy(false) to all your + * LayoutTransitions?". + */ +final class AnimateLayoutChangeDetector { + private static final ViewGroup.MarginLayoutParams ZERO_MARGIN_LAYOUT_PARAMS; + + static { + ZERO_MARGIN_LAYOUT_PARAMS = new ViewGroup.MarginLayoutParams(MATCH_PARENT, MATCH_PARENT); + ZERO_MARGIN_LAYOUT_PARAMS.setMargins(0, 0, 0, 0); + } + + private ViewPager2LinearLayoutManager mLayoutManager; + + AnimateLayoutChangeDetector(@NonNull ViewPager2LinearLayoutManager llm) { + mLayoutManager = llm; + } + + boolean mayHaveInterferingAnimations() { + // Two conditions need to be satisfied: + // 1) the pages are not laid out contiguously (i.e., there are gaps between them) + // 2) there is a ViewGroup with a LayoutTransition that isChangingLayout() + return (!arePagesLaidOutContiguously() || mLayoutManager.getChildCount() <= 1) + && hasRunningChangingLayoutTransition(); + } + + private boolean arePagesLaidOutContiguously() { + // Collect view positions + int childCount = mLayoutManager.getChildCount(); + if (childCount == 0) { + return true; + } + + boolean isHorizontal = mLayoutManager.getOrientation() == ORIENTATION_HORIZONTAL; + int[][] bounds = new int[childCount][2]; + for (int i = 0; i < childCount; i++) { + View view = mLayoutManager.getChildAt(i); + if (view == null) { + throw new IllegalStateException("null view contained in the view hierarchy"); + } + ViewGroup.LayoutParams layoutParams = view.getLayoutParams(); + ViewGroup.MarginLayoutParams margin; + if (layoutParams instanceof ViewGroup.MarginLayoutParams) { + margin = (ViewGroup.MarginLayoutParams) layoutParams; + } else { + margin = ZERO_MARGIN_LAYOUT_PARAMS; + } + bounds[i][0] = isHorizontal + ? view.getLeft() - margin.leftMargin + : view.getTop() - margin.topMargin; + bounds[i][1] = isHorizontal + ? view.getRight() + margin.rightMargin + : view.getBottom() + margin.bottomMargin; + } + + // Sort them + Arrays.sort(bounds, new Comparator() { + @Override + public int compare(int[] lhs, int[] rhs) { + return lhs[0] - rhs[0]; + } + }); + + // Check for inconsistencies + for (int i = 1; i < childCount; i++) { + if (bounds[i - 1][1] != bounds[i][0]) { + return false; + } + } + + // Check that the pages fill the whole screen + int pageSize = bounds[0][1] - bounds[0][0]; + if (bounds[0][0] > 0 || bounds[childCount - 1][1] < pageSize) { + return false; + } + return true; + } + + private boolean hasRunningChangingLayoutTransition() { + int childCount = mLayoutManager.getChildCount(); + for (int i = 0; i < childCount; i++) { + if (hasRunningChangingLayoutTransition(mLayoutManager.getChildAt(i))) { + return true; + } + } + return false; + } + + private static boolean hasRunningChangingLayoutTransition(View view) { + if (view instanceof ViewGroup) { + ViewGroup viewGroup = (ViewGroup) view; + LayoutTransition layoutTransition = viewGroup.getLayoutTransition(); + if (layoutTransition != null && layoutTransition.isChangingLayout()) { + return true; + } + int childCount = viewGroup.getChildCount(); + for (int i = 0; i < childCount; i++) { + if (hasRunningChangingLayoutTransition(viewGroup.getChildAt(i))) { + return true; + } + } + } + return false; + } +} \ No newline at end of file diff --git a/viewpager2/src/main/java/com/vinsonguo/viewpager2/widget/CompositeOnPageChangeCallback.java b/viewpager2/src/main/java/com/vinsonguo/viewpager2/widget/CompositeOnPageChangeCallback.java new file mode 100644 index 0000000..0928740 --- /dev/null +++ b/viewpager2/src/main/java/com/vinsonguo/viewpager2/widget/CompositeOnPageChangeCallback.java @@ -0,0 +1,100 @@ +package com.vinsonguo.viewpager2.widget; +/* + * Copyright 2019 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +import android.support.annotation.NonNull; +import android.support.annotation.Px; + +import java.util.ArrayList; +import java.util.ConcurrentModificationException; +import java.util.List; + +/** + * Dispatches {@link ViewPager2.OnPageChangeCallback} events to subscribers. + */ +final class CompositeOnPageChangeCallback extends ViewPager2.OnPageChangeCallback { + @NonNull + private final List mCallbacks; + + CompositeOnPageChangeCallback(int initialCapacity) { + mCallbacks = new ArrayList<>(initialCapacity); + } + + /** + * Adds the given callback to the list of subscribers + */ + void addOnPageChangeCallback(ViewPager2.OnPageChangeCallback callback) { + mCallbacks.add(callback); + } + + /** + * Removes the given callback from the list of subscribers + */ + void removeOnPageChangeCallback(ViewPager2.OnPageChangeCallback callback) { + mCallbacks.remove(callback); + } + + /** + * @see ViewPager2.OnPageChangeCallback#onPageScrolled(int, float, int) + */ + @Override + public void onPageScrolled(int position, float positionOffset, @Px int positionOffsetPixels) { + try { + for (ViewPager2.OnPageChangeCallback callback : mCallbacks) { + callback.onPageScrolled(position, positionOffset, positionOffsetPixels); + } + } catch (ConcurrentModificationException ex) { + throwCallbackListModifiedWhileInUse(ex); + } + } + + /** + * @see ViewPager2.OnPageChangeCallback#onPageSelected(int) + */ + @Override + public void onPageSelected(int position) { + try { + for (ViewPager2.OnPageChangeCallback callback : mCallbacks) { + callback.onPageSelected(position); + } + } catch (ConcurrentModificationException ex) { + throwCallbackListModifiedWhileInUse(ex); + } + } + + /** + * @see ViewPager2.OnPageChangeCallback#onPageScrollStateChanged(int) + */ + @Override + public void onPageScrollStateChanged(@ViewPager2.ScrollState int state) { + try { + for (ViewPager2.OnPageChangeCallback callback : mCallbacks) { + callback.onPageScrollStateChanged(state); + } + } catch (ConcurrentModificationException ex) { + throwCallbackListModifiedWhileInUse(ex); + } + } + + private void throwCallbackListModifiedWhileInUse(ConcurrentModificationException parent) { + throw new IllegalStateException( + "Adding and removing callbacks during dispatch to callbacks is not supported", + parent + ); + } + +} diff --git a/viewpager2/src/main/java/com/vinsonguo/viewpager2/widget/CompositePageTransformer.java b/viewpager2/src/main/java/com/vinsonguo/viewpager2/widget/CompositePageTransformer.java new file mode 100644 index 0000000..f5cc7ee --- /dev/null +++ b/viewpager2/src/main/java/com/vinsonguo/viewpager2/widget/CompositePageTransformer.java @@ -0,0 +1,39 @@ +package com.vinsonguo.viewpager2.widget; +import android.support.annotation.NonNull; +import android.view.View; + + +import java.util.ArrayList; +import java.util.List; + +/** + * Allows for combining multiple {@link PageTransformer} objects. + * + * @see ViewPager2#setPageTransformer + * @see MarginPageTransformer + */ +public final class CompositePageTransformer implements ViewPager2.PageTransformer { + private final List mTransformers = new ArrayList<>(); + + /** + * Adds a page transformer to the list. + *

+ * Transformers will be executed in the order that they were added. + */ + public void addTransformer(@NonNull ViewPager2.PageTransformer transformer) { + mTransformers.add(transformer); + } + + /** Removes a page transformer from the list. */ + public void removeTransformer(@NonNull ViewPager2.PageTransformer transformer) { + mTransformers.remove(transformer); + } + + @Override + public void transformPage(@NonNull View page, float position) { + for (ViewPager2.PageTransformer transformer : mTransformers) { + transformer.transformPage(page, position); + } + } +} + diff --git a/viewpager2/src/main/java/com/vinsonguo/viewpager2/widget/FakeDrag.java b/viewpager2/src/main/java/com/vinsonguo/viewpager2/widget/FakeDrag.java new file mode 100644 index 0000000..e11b269 --- /dev/null +++ b/viewpager2/src/main/java/com/vinsonguo/viewpager2/widget/FakeDrag.java @@ -0,0 +1,122 @@ +package com.vinsonguo.viewpager2.widget; + +import static com.vinsonguo.viewpager2.widget.ViewPager2.ORIENTATION_HORIZONTAL; + +import android.os.SystemClock; +import android.support.annotation.UiThread; +import android.support.v7.widget.RecyclerView; +import android.view.MotionEvent; +import android.view.VelocityTracker; +import android.view.ViewConfiguration; + + +/** + * Provides fake dragging functionality to {@link ViewPager2}. + */ +final class FakeDrag { + private final ViewPager2 mViewPager; + private final ScrollEventAdapter mScrollEventAdapter; + private final RecyclerView mRecyclerView; + + private VelocityTracker mVelocityTracker; + private int mMaximumVelocity; + private float mRequestedDragDistance; + private int mActualDraggedDistance; + private long mFakeDragBeginTime; + + FakeDrag(ViewPager2 viewPager, ScrollEventAdapter scrollEventAdapter, + RecyclerView recyclerView) { + mViewPager = viewPager; + mScrollEventAdapter = scrollEventAdapter; + mRecyclerView = recyclerView; + } + + boolean isFakeDragging() { + return mScrollEventAdapter.isFakeDragging(); + } + + @UiThread + boolean beginFakeDrag() { + if (mScrollEventAdapter.isDragging()) { + return false; + } + mRequestedDragDistance = mActualDraggedDistance = 0; + mFakeDragBeginTime = SystemClock.uptimeMillis(); + beginFakeVelocityTracker(); + + mScrollEventAdapter.notifyBeginFakeDrag(); + if (!mScrollEventAdapter.isIdle()) { + // Stop potentially running settling animation + mRecyclerView.stopScroll(); + } + addFakeMotionEvent(mFakeDragBeginTime, MotionEvent.ACTION_DOWN, 0, 0); + return true; + } + + @UiThread + boolean fakeDragBy(float offsetPxFloat) { + if (!mScrollEventAdapter.isFakeDragging()) { + // Can happen legitimately if user started dragging during fakeDrag and app is still + // sending fakeDragBy commands + return false; + } + // Subtract the offset, because content scrolls in the opposite direction of finger motion + mRequestedDragDistance -= offsetPxFloat; + // Calculate amount of pixels to scroll ... + int offsetPx = Math.round(mRequestedDragDistance - mActualDraggedDistance); + // ... and keep track of pixels scrolled so we don't get rounding errors + mActualDraggedDistance += offsetPx; + long time = SystemClock.uptimeMillis(); + + boolean isHorizontal = mViewPager.getOrientation() == ORIENTATION_HORIZONTAL; + // Scroll deltas use pixels: + final int offsetX = isHorizontal ? offsetPx : 0; + final int offsetY = isHorizontal ? 0 : offsetPx; + // Motion events get the raw float distance: + final float x = isHorizontal ? mRequestedDragDistance : 0; + final float y = isHorizontal ? 0 : mRequestedDragDistance; + + mRecyclerView.scrollBy(offsetX, offsetY); + addFakeMotionEvent(time, MotionEvent.ACTION_MOVE, x, y); + return true; + } + + @UiThread + boolean endFakeDrag() { + if (!mScrollEventAdapter.isFakeDragging()) { + // Happens legitimately if user started dragging during fakeDrag + return false; + } + + mScrollEventAdapter.notifyEndFakeDrag(); + + // Compute the velocity of the fake drag + final int pixelsPerSecond = 1000; + final VelocityTracker velocityTracker = mVelocityTracker; + velocityTracker.computeCurrentVelocity(pixelsPerSecond, mMaximumVelocity); + int xVelocity = (int) velocityTracker.getXVelocity(); + int yVelocity = (int) velocityTracker.getYVelocity(); + // And fling or snap the ViewPager2 to its destination + if (!mRecyclerView.fling(xVelocity, yVelocity)) { + // Velocity too low, trigger snap to page manually + mViewPager.snapToPage(); + } + return true; + } + + private void beginFakeVelocityTracker() { + if (mVelocityTracker == null) { + mVelocityTracker = VelocityTracker.obtain(); + final ViewConfiguration configuration = ViewConfiguration.get(mViewPager.getContext()); + mMaximumVelocity = configuration.getScaledMaximumFlingVelocity(); + } else { + mVelocityTracker.clear(); + } + } + + private void addFakeMotionEvent(long time, int action, float x, float y) { + final MotionEvent ev = MotionEvent.obtain(mFakeDragBeginTime, time, action, x, y, 0); + mVelocityTracker.addMovement(ev); + ev.recycle(); + } +} diff --git a/viewpager2/src/main/java/com/vinsonguo/viewpager2/widget/MarginPageTransformer.java b/viewpager2/src/main/java/com/vinsonguo/viewpager2/widget/MarginPageTransformer.java new file mode 100644 index 0000000..1201fe9 --- /dev/null +++ b/viewpager2/src/main/java/com/vinsonguo/viewpager2/widget/MarginPageTransformer.java @@ -0,0 +1,59 @@ +package com.vinsonguo.viewpager2.widget; +import android.support.annotation.NonNull; +import android.support.annotation.Px; +import android.support.v4.util.Preconditions; +import android.support.v7.widget.RecyclerView; +import android.view.View; +import android.view.ViewParent; + + +/** + * Adds space between pages via the {@link ViewPager2.PageTransformer} API. + *

+ * Internally relies on {@link View#setTranslationX} and {@link View#setTranslationY}. + *

+ * Note: translations on pages are not reset when this adapter is changed for another one, so you + * might want to set them manually to 0 when dynamically switching to another transformer, or + * when switching ViewPager2 orientation. + * + * @see ViewPager2#setPageTransformer + * @see CompositePageTransformer + */ +public final class MarginPageTransformer implements ViewPager2.PageTransformer { + private final int mMarginPx; + + /** + * Creates a {@link MarginPageTransformer}. + * + * @param marginPx non-negative margin + */ + public MarginPageTransformer(@Px int marginPx) { + Preconditions.checkArgumentNonnegative(marginPx, "Margin must be non-negative"); + mMarginPx = marginPx; + } + + @Override + public void transformPage(@NonNull View page, float position) { + ViewPager2 viewPager = requireViewPager(page); + + float offset = mMarginPx * position; + + if (viewPager.getOrientation() == ViewPager2.ORIENTATION_HORIZONTAL) { + page.setTranslationX(viewPager.isRtl() ? -offset : offset); + } else { + page.setTranslationY(offset); + } + } + + private ViewPager2 requireViewPager(@NonNull View page) { + ViewParent parent = page.getParent(); + ViewParent parentParent = parent.getParent(); + + if (parent instanceof RecyclerView && parentParent instanceof ViewPager2) { + return (ViewPager2) parentParent; + } + + throw new IllegalStateException( + "Expected the page view to be managed by a ViewPager2 instance."); + } +} diff --git a/viewpager2/src/main/java/com/vinsonguo/viewpager2/widget/PageTransformerAdapter.java b/viewpager2/src/main/java/com/vinsonguo/viewpager2/widget/PageTransformerAdapter.java new file mode 100644 index 0000000..92322f2 --- /dev/null +++ b/viewpager2/src/main/java/com/vinsonguo/viewpager2/widget/PageTransformerAdapter.java @@ -0,0 +1,65 @@ +package com.vinsonguo.viewpager2.widget; +import android.support.annotation.Nullable; +import android.support.v7.widget.LinearLayoutManager; +import android.support.v7.widget.ViewPager2LinearLayoutManager; +import android.view.View; + + +import java.util.Locale; + +/** + * Translates {@link OnPageChangeCallback} events to {@link PageTransformer} events. + */ +final class PageTransformerAdapter extends ViewPager2.OnPageChangeCallback { + private final ViewPager2LinearLayoutManager mLayoutManager; + + private ViewPager2.PageTransformer mPageTransformer; + + PageTransformerAdapter(ViewPager2LinearLayoutManager layoutManager) { + mLayoutManager = layoutManager; + } + + ViewPager2.PageTransformer getPageTransformer() { + return mPageTransformer; + } + + /** + * Sets the PageTransformer. The page transformer will be called for each attached page whenever + * the scroll position is changed. + * + * @param transformer The PageTransformer + */ + void setPageTransformer(@Nullable ViewPager2.PageTransformer transformer) { + // TODO: add support for reverseDrawingOrder: b/112892792 + // TODO: add support for pageLayerType: b/112893074 + mPageTransformer = transformer; + } + + @Override + public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { + if (mPageTransformer == null) { + return; + } + + float transformOffset = -positionOffset; + for (int i = 0; i < mLayoutManager.getChildCount(); i++) { + View view = mLayoutManager.getChildAt(i); + if (view == null) { + throw new IllegalStateException(String.format(Locale.US, + "LayoutManager returned a null child at pos %d/%d while transforming pages", + i, mLayoutManager.getChildCount())); + } + int currPos = mLayoutManager.getPosition(view); + float viewOffset = transformOffset + (currPos - position); + mPageTransformer.transformPage(view, viewOffset); + } + } + + @Override + public void onPageSelected(int position) { + } + + @Override + public void onPageScrollStateChanged(int state) { + } +} \ No newline at end of file diff --git a/viewpager2/src/main/java/com/vinsonguo/viewpager2/widget/ScrollEventAdapter.java b/viewpager2/src/main/java/com/vinsonguo/viewpager2/widget/ScrollEventAdapter.java new file mode 100644 index 0000000..21b6dce --- /dev/null +++ b/viewpager2/src/main/java/com/vinsonguo/viewpager2/widget/ScrollEventAdapter.java @@ -0,0 +1,444 @@ +package com.vinsonguo.viewpager2.widget; + +import static com.vinsonguo.viewpager2.widget.ViewPager2.ORIENTATION_HORIZONTAL; +import static com.vinsonguo.viewpager2.widget.ViewPager2.SCROLL_STATE_DRAGGING; +import static com.vinsonguo.viewpager2.widget.ViewPager2.SCROLL_STATE_IDLE; +import static com.vinsonguo.viewpager2.widget.ViewPager2.SCROLL_STATE_SETTLING; +import static java.lang.annotation.RetentionPolicy.SOURCE; + +import android.support.annotation.IntDef; +import android.support.annotation.NonNull; +import android.support.v7.widget.LinearLayoutManager; +import android.support.v7.widget.RecyclerView; +import android.support.v7.widget.ViewPager2LinearLayoutManager; +import android.view.View; +import android.view.ViewGroup.LayoutParams; +import android.view.ViewGroup.MarginLayoutParams; + + +import java.lang.annotation.Retention; +import java.util.Locale; + +/** + * Translates {@link RecyclerView.OnScrollListener} events to {@link OnPageChangeCallback} events + * for {@link ViewPager2}. As part of this process, it keeps track of the current scroll position + * relative to the pages and exposes this position via ({@link #getRelativeScrollPosition()}. + */ +final class ScrollEventAdapter extends RecyclerView.OnScrollListener { + /** @hide */ + @Retention(SOURCE) + @IntDef({STATE_IDLE, STATE_IN_PROGRESS_MANUAL_DRAG, STATE_IN_PROGRESS_SMOOTH_SCROLL, + STATE_IN_PROGRESS_IMMEDIATE_SCROLL, STATE_IN_PROGRESS_FAKE_DRAG}) + private @interface AdapterState { + } + + private static final int STATE_IDLE = 0; + private static final int STATE_IN_PROGRESS_MANUAL_DRAG = 1; + private static final int STATE_IN_PROGRESS_SMOOTH_SCROLL = 2; + private static final int STATE_IN_PROGRESS_IMMEDIATE_SCROLL = 3; + private static final int STATE_IN_PROGRESS_FAKE_DRAG = 4; + + private static final int NO_POSITION = -1; + + private ViewPager2.OnPageChangeCallback mCallback; + private final @NonNull ViewPager2 mViewPager; + private final @NonNull RecyclerView mRecyclerView; + private final @NonNull + ViewPager2LinearLayoutManager mLayoutManager; + + // state related fields + private @AdapterState int mAdapterState; + private @ViewPager2.ScrollState int mScrollState; + private ScrollEventValues mScrollValues; + private int mDragStartPosition; + private int mTarget; + private boolean mDispatchSelected; + private boolean mScrollHappened; + private boolean mDataSetChangeHappened; + private boolean mFakeDragging; + + ScrollEventAdapter(@NonNull ViewPager2 viewPager) { + mViewPager = viewPager; + mRecyclerView = mViewPager.mRecyclerView; + //noinspection ConstantConditions + mLayoutManager = (ViewPager2LinearLayoutManager) mRecyclerView.getLayoutManager(); + mScrollValues = new ScrollEventValues(); + resetState(); + } + + private void resetState() { + mAdapterState = STATE_IDLE; + mScrollState = SCROLL_STATE_IDLE; + mScrollValues.reset(); + mDragStartPosition = NO_POSITION; + mTarget = NO_POSITION; + mDispatchSelected = false; + mScrollHappened = false; + mFakeDragging = false; + mDataSetChangeHappened = false; + } + + /** + * This method only deals with some cases of {@link AdapterState} transitions. The rest of + * the state transition implementation is in the {@link #onScrolled} method. + */ + @Override + public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) { + // User started a drag (not dragging -> dragging) + if ((mAdapterState != STATE_IN_PROGRESS_MANUAL_DRAG + || mScrollState != SCROLL_STATE_DRAGGING) + && newState == RecyclerView.SCROLL_STATE_DRAGGING) { + startDrag(false); + return; + } + + // Drag is released, RecyclerView is snapping to page (dragging -> settling) + // Note that mAdapterState is not updated, to remember we were dragging when settling + if (isInAnyDraggingState() && newState == RecyclerView.SCROLL_STATE_SETTLING) { + // Only go through the settling phase if the drag actually moved the page + if (mScrollHappened) { + dispatchStateChanged(SCROLL_STATE_SETTLING); + // Determine target page and dispatch onPageSelected on next scroll event + mDispatchSelected = true; + } + return; + } + + // Drag is finished (dragging || settling -> idle) + if (isInAnyDraggingState() && newState == RecyclerView.SCROLL_STATE_IDLE) { + boolean dispatchIdle = false; + updateScrollEventValues(); + if (!mScrollHappened) { + // Pages didn't move during drag, so either we're at the start or end of the list, + // or there are no pages at all. + // In the first case, ViewPager's contract requires at least one scroll event. + // In the second case, don't send that scroll event + if (mScrollValues.mPosition != RecyclerView.NO_POSITION) { + dispatchScrolled(mScrollValues.mPosition, 0f, 0); + } + dispatchIdle = true; + } else if (mScrollValues.mOffsetPx == 0) { + // Normally we dispatch the selected page and go to idle in onScrolled when + // mOffsetPx == 0, but in this case the drag was still ongoing when onScrolled was + // called, so that didn't happen. And since mOffsetPx == 0, there will be no further + // scroll events, so fire the onPageSelected event and go to idle now. + // Note that if we _did_ go to idle in that last onScrolled event, this code will + // not be executed because mAdapterState has been reset to STATE_IDLE. + dispatchIdle = true; + if (mDragStartPosition != mScrollValues.mPosition) { + dispatchSelected(mScrollValues.mPosition); + } + } + if (dispatchIdle) { + // Normally idle is fired in last onScrolled call, but either onScrolled was never + // called, or we were still dragging when the last onScrolled was called + dispatchStateChanged(SCROLL_STATE_IDLE); + resetState(); + } + } + + if (mAdapterState == STATE_IN_PROGRESS_SMOOTH_SCROLL + && newState == RecyclerView.SCROLL_STATE_IDLE && mDataSetChangeHappened) { + updateScrollEventValues(); + if (mScrollValues.mOffsetPx == 0) { + if (mTarget != mScrollValues.mPosition) { + dispatchSelected( + mScrollValues.mPosition == NO_POSITION ? 0 : mScrollValues.mPosition); + } + dispatchStateChanged(SCROLL_STATE_IDLE); + resetState(); + } + } + } + + /** + * This method only deals with some cases of {@link AdapterState} transitions. The rest of + * the state transition implementation is in the {@link #onScrollStateChanged} method. + */ + @Override + public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { + mScrollHappened = true; + updateScrollEventValues(); + + if (mDispatchSelected) { + // Drag started settling, need to calculate target page and dispatch onPageSelected now + mDispatchSelected = false; + boolean scrollingForward = dy > 0 || (dy == 0 && dx < 0 == mViewPager.isRtl()); + + // "&& values.mOffsetPx != 0": filters special case where we're scrolling forward and + // the first scroll event after settling already got us at the target + mTarget = scrollingForward && mScrollValues.mOffsetPx != 0 + ? mScrollValues.mPosition + 1 : mScrollValues.mPosition; + if (mDragStartPosition != mTarget) { + dispatchSelected(mTarget); + } + } else if (mAdapterState == STATE_IDLE) { + // onScrolled while IDLE means RV has just been populated after an adapter has been set. + // Contract requires us to fire onPageSelected as well. + int position = mScrollValues.mPosition; + // Contract forbids us to send position = -1 though + dispatchSelected(position == NO_POSITION ? 0 : position); + } + + // If position = -1, there are no items. Contract says to send position = 0 instead. + dispatchScrolled(mScrollValues.mPosition == NO_POSITION ? 0 : mScrollValues.mPosition, + mScrollValues.mOffset, mScrollValues.mOffsetPx); + + // Dispatch idle in onScrolled instead of in onScrollStateChanged because RecyclerView + // doesn't send IDLE event when using setCurrentItem(x, false) + if ((mScrollValues.mPosition == mTarget || mTarget == NO_POSITION) + && mScrollValues.mOffsetPx == 0 && !(mScrollState == SCROLL_STATE_DRAGGING)) { + // When the target page is reached and the user is not dragging anymore, we're settled, + // so go to idle. + // Special case and a bit of a hack when mTarget == NO_POSITION: RecyclerView is being + // initialized and fires a single scroll event. This flags mScrollHappened, so we need + // to reset our state. However, we don't want to dispatch idle. But that won't happen; + // because we were already idle. + dispatchStateChanged(SCROLL_STATE_IDLE); + resetState(); + } + } + + /** + * Calculates the current position and the offset (as a percentage and in pixels) of that + * position from the center. + */ + private void updateScrollEventValues() { + ScrollEventValues values = mScrollValues; + + values.mPosition = mLayoutManager.findFirstVisibleItemPosition(); + if (values.mPosition == RecyclerView.NO_POSITION) { + values.reset(); + return; + } + View firstVisibleView = mLayoutManager.findViewByPosition(values.mPosition); + if (firstVisibleView == null) { + values.reset(); + return; + } + + int leftDecorations = mLayoutManager.getLeftDecorationWidth(firstVisibleView); + int rightDecorations = mLayoutManager.getRightDecorationWidth(firstVisibleView); + int topDecorations = mLayoutManager.getTopDecorationHeight(firstVisibleView); + int bottomDecorations = mLayoutManager.getBottomDecorationHeight(firstVisibleView); + + LayoutParams params = firstVisibleView.getLayoutParams(); + if (params instanceof MarginLayoutParams) { + MarginLayoutParams margin = (MarginLayoutParams) params; + leftDecorations += margin.leftMargin; + rightDecorations += margin.rightMargin; + topDecorations += margin.topMargin; + bottomDecorations += margin.bottomMargin; + } + + int decoratedHeight = firstVisibleView.getHeight() + topDecorations + bottomDecorations; + int decoratedWidth = firstVisibleView.getWidth() + leftDecorations + rightDecorations; + + boolean isHorizontal = mLayoutManager.getOrientation() == ORIENTATION_HORIZONTAL; + int start, sizePx; + if (isHorizontal) { + sizePx = decoratedWidth; + start = firstVisibleView.getLeft() - leftDecorations - mRecyclerView.getPaddingLeft(); + if (mViewPager.isRtl()) { + start = -start; + } + } else { + sizePx = decoratedHeight; + start = firstVisibleView.getTop() - topDecorations - mRecyclerView.getPaddingTop(); + } + + values.mOffsetPx = -start; + if (values.mOffsetPx < 0) { + // We're in an error state. Figure out if this might have been caused + // by animateLayoutChanges and throw a descriptive exception if so + if (new AnimateLayoutChangeDetector(mLayoutManager).mayHaveInterferingAnimations()) { + throw new IllegalStateException("Page(s) contain a ViewGroup with a " + + "LayoutTransition (or animateLayoutChanges=\"true\"), which interferes " + + "with the scrolling animation. Make sure to call getLayoutTransition()" + + ".setAnimateParentHierarchy(false) on all ViewGroups with a " + + "LayoutTransition before an animation is started."); + } + + // Throw a generic exception otherwise + throw new IllegalStateException(String.format(Locale.US, "Page can only be offset by a " + + "positive amount, not by %d", values.mOffsetPx)); + } + values.mOffset = sizePx == 0 ? 0 : (float) values.mOffsetPx / sizePx; + } + + private void startDrag(boolean isFakeDrag) { + mFakeDragging = isFakeDrag; + mAdapterState = isFakeDrag ? STATE_IN_PROGRESS_FAKE_DRAG : STATE_IN_PROGRESS_MANUAL_DRAG; + if (mTarget != NO_POSITION) { + // Target was set means we were settling to that target + // Update "drag start page" to reflect the page that ViewPager2 thinks it is at + mDragStartPosition = mTarget; + // Reset target because drags have no target until released + mTarget = NO_POSITION; + } else if (mDragStartPosition == NO_POSITION) { + // ViewPager2 was at rest, set "drag start page" to current page + mDragStartPosition = getPosition(); + } + dispatchStateChanged(SCROLL_STATE_DRAGGING); + } + + void notifyDataSetChangeHappened() { + mDataSetChangeHappened = true; + } + + /** + * Let the adapter know a programmatic scroll was initiated. + */ + void notifyProgrammaticScroll(int target, boolean smooth) { + mAdapterState = smooth + ? STATE_IN_PROGRESS_SMOOTH_SCROLL + : STATE_IN_PROGRESS_IMMEDIATE_SCROLL; + // mFakeDragging is true when a fake drag is interrupted by an a11y command + // set it to false so endFakeDrag won't fling the RecyclerView + mFakeDragging = false; + boolean hasNewTarget = mTarget != target; + mTarget = target; + dispatchStateChanged(SCROLL_STATE_SETTLING); + if (hasNewTarget) { + dispatchSelected(target); + } + } + + /** + * Let the adapter know that a fake drag has started. + */ + void notifyBeginFakeDrag() { + mAdapterState = STATE_IN_PROGRESS_FAKE_DRAG; + startDrag(true); + } + + /** + * Let the adapter know that a fake drag has ended. + */ + void notifyEndFakeDrag() { + if (isDragging() && !mFakeDragging) { + // Real drag has already taken over, no need to post process the fake drag + return; + } + mFakeDragging = false; + updateScrollEventValues(); + if (mScrollValues.mOffsetPx == 0) { + // We're snapped, so dispatch an IDLE event + if (mScrollValues.mPosition != mDragStartPosition) { + dispatchSelected(mScrollValues.mPosition); + } + dispatchStateChanged(SCROLL_STATE_IDLE); + resetState(); + } else { + // We're not snapped, so dispatch a SETTLING event + dispatchStateChanged(SCROLL_STATE_SETTLING); + } + } + + void setOnPageChangeCallback(ViewPager2.OnPageChangeCallback callback) { + mCallback = callback; + } + + int getScrollState() { + return mScrollState; + } + + /** + * @return {@code true} if there is no known scroll in progress + */ + boolean isIdle() { + return mScrollState == SCROLL_STATE_IDLE; + } + + /** + * @return {@code true} if the ViewPager2 is being dragged. Returns {@code false} from the + * moment the ViewPager2 starts settling or goes idle. + */ + boolean isDragging() { + return mScrollState == SCROLL_STATE_DRAGGING; + } + + /** + * @return {@code true} if a fake drag is ongoing. Returns {@code false} from the moment the + * {@link ViewPager2#endFakeDrag()} is called. + */ + boolean isFakeDragging() { + return mFakeDragging; + } + + /** + * Checks if the adapter state (not the scroll state) is in the manual or fake dragging state. + * @return {@code true} if {@link #mAdapterState} is either {@link + * #STATE_IN_PROGRESS_MANUAL_DRAG} or {@link #STATE_IN_PROGRESS_FAKE_DRAG} + */ + private boolean isInAnyDraggingState() { + return mAdapterState == STATE_IN_PROGRESS_MANUAL_DRAG + || mAdapterState == STATE_IN_PROGRESS_FAKE_DRAG; + } + + /** + * Calculates the scroll position of the currently visible item of the ViewPager relative to its + * width. Calculated by adding the fraction by which the first visible item is off screen to its + * adapter position. E.g., if the ViewPager is currently scrolling from the second to the third + * page, the returned value will be between 1 and 2. Thus, non-integral values mean that the + * the ViewPager is settling towards its {@link ViewPager2#getCurrentItem() current item}, or + * the user may be dragging it. + * + * @return The current scroll position of the ViewPager, relative to its width + */ + double getRelativeScrollPosition() { + updateScrollEventValues(); + return mScrollValues.mPosition + (double) mScrollValues.mOffset; + } + + private void dispatchStateChanged(@ViewPager2.ScrollState int state) { + // Callback contract for immediate-scroll requires not having state change notifications, + // but only when there was no smooth scroll in progress. + // By putting a suppress statement in here (rather than next to dispatch calls) we are + // simplifying the code of the class and enforcing the contract in one place. + if (mAdapterState == STATE_IN_PROGRESS_IMMEDIATE_SCROLL + && mScrollState == SCROLL_STATE_IDLE) { + return; + } + if (mScrollState == state) { + return; + } + + mScrollState = state; + if (mCallback != null) { + mCallback.onPageScrollStateChanged(state); + } + } + + private void dispatchSelected(int target) { + if (mCallback != null) { + mCallback.onPageSelected(target); + } + } + + private void dispatchScrolled(int position, float offset, int offsetPx) { + if (mCallback != null) { + mCallback.onPageScrolled(position, offset, offsetPx); + } + } + + private int getPosition() { + return mLayoutManager.findFirstVisibleItemPosition(); + } + + private static final class ScrollEventValues { + int mPosition; + float mOffset; + int mOffsetPx; + + // to avoid a synthetic accessor + ScrollEventValues() { + } + + void reset() { + mPosition = RecyclerView.NO_POSITION; + mOffset = 0f; + mOffsetPx = 0; + } + } +} \ No newline at end of file diff --git a/viewpager2/src/main/java/com/vinsonguo/viewpager2/widget/ViewPager2.java b/viewpager2/src/main/java/com/vinsonguo/viewpager2/widget/ViewPager2.java new file mode 100644 index 0000000..aef1324 --- /dev/null +++ b/viewpager2/src/main/java/com/vinsonguo/viewpager2/widget/ViewPager2.java @@ -0,0 +1,1360 @@ +package com.vinsonguo.viewpager2.widget; +/* + * Copyright 2017 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +import static android.support.annotation.RestrictTo.Scope.LIBRARY; +import static android.support.v7.widget.RecyclerView.NO_POSITION; + +import static java.lang.annotation.RetentionPolicy.SOURCE; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.content.res.TypedArray; +import android.graphics.Rect; +import android.os.Build; +import android.os.Bundle; +import android.os.Parcel; +import android.os.Parcelable; +import android.support.annotation.IntDef; +import android.support.annotation.IntRange; +import android.support.annotation.NonNull; +import android.support.annotation.Nullable; +import android.support.annotation.Px; +import android.support.annotation.RequiresApi; +import android.support.annotation.RestrictTo; +import android.support.v4.view.ViewCompat; +import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat; +import android.support.v7.widget.LinearLayoutManager; +import android.support.v7.widget.PagerSnapHelper; +import android.support.v7.widget.RecyclerView; +import android.support.v7.widget.ViewPager2LinearLayoutManager; +import android.util.AttributeSet; +import android.util.SparseArray; +import android.view.Gravity; +import android.view.MotionEvent; +import android.view.View; +import android.view.ViewGroup; +import android.view.accessibility.AccessibilityEvent; +import android.view.accessibility.AccessibilityNodeInfo; + +import com.vinsonguo.viewpager2.R; +import com.vinsonguo.viewpager2.adapter.StatefulAdapter; + +import java.lang.annotation.Retention; + +/** + * ViewPager2 replaces {@link androidx.viewpager.widget.ViewPager}, addressing most of its + * predecessor’s pain-points, including right-to-left layout support, vertical orientation, + * modifiable Fragment collections, etc. + * + * @see androidx.viewpager.widget.ViewPager + */ +public final class ViewPager2 extends ViewGroup { + /** @hide */ + @RestrictTo(LIBRARY) + @Retention(SOURCE) + @IntDef({ORIENTATION_HORIZONTAL, ORIENTATION_VERTICAL}) + public @interface Orientation { + } + + public static final int ORIENTATION_HORIZONTAL = RecyclerView.HORIZONTAL; + public static final int ORIENTATION_VERTICAL = RecyclerView.VERTICAL; + + /** @hide */ + @RestrictTo(LIBRARY) + @Retention(SOURCE) + @IntDef({SCROLL_STATE_IDLE, SCROLL_STATE_DRAGGING, SCROLL_STATE_SETTLING}) + public @interface ScrollState { + } + + /** @hide */ + @SuppressWarnings("WeakerAccess") + @RestrictTo(LIBRARY) + @Retention(SOURCE) + @IntDef({OFFSCREEN_PAGE_LIMIT_DEFAULT}) + @IntRange(from = 1) + public @interface OffscreenPageLimit { + } + + /** + * Indicates that the ViewPager2 is in an idle, settled state. The current page + * is fully in view and no animation is in progress. + */ + public static final int SCROLL_STATE_IDLE = 0; + + /** + * Indicates that the ViewPager2 is currently being dragged by the user, or programmatically + * via fake drag functionality. + */ + public static final int SCROLL_STATE_DRAGGING = 1; + + /** + * Indicates that the ViewPager2 is in the process of settling to a final position. + */ + public static final int SCROLL_STATE_SETTLING = 2; + + /** + * Value to indicate that the default caching mechanism of RecyclerView should be used instead + * of explicitly prefetch and retain pages to either side of the current page. + * @see #setOffscreenPageLimit(int) + */ + public static final int OFFSCREEN_PAGE_LIMIT_DEFAULT = -1; + + /** Feature flag while stabilizing enhanced a11y */ + static boolean sFeatureEnhancedA11yEnabled = true; + + // reused in layout(...) + private final Rect mTmpContainerRect = new Rect(); + private final Rect mTmpChildRect = new Rect(); + + private CompositeOnPageChangeCallback mExternalPageChangeCallbacks = + new CompositeOnPageChangeCallback(3); + + int mCurrentItem; + boolean mCurrentItemDirty = false; + private RecyclerView.AdapterDataObserver mCurrentItemDataSetChangeObserver = + new DataSetChangeObserver() { + @Override + public void onChanged() { + mCurrentItemDirty = true; + mScrollEventAdapter.notifyDataSetChangeHappened(); + } + }; + + private ViewPager2LinearLayoutManager mLayoutManager; + private int mPendingCurrentItem = NO_POSITION; + private Parcelable mPendingAdapterState; + RecyclerView mRecyclerView; + private PagerSnapHelper mPagerSnapHelper; + ScrollEventAdapter mScrollEventAdapter; + private CompositeOnPageChangeCallback mPageChangeEventDispatcher; + private FakeDrag mFakeDragger; + private PageTransformerAdapter mPageTransformerAdapter; + private RecyclerView.ItemAnimator mSavedItemAnimator = null; + private boolean mSavedItemAnimatorPresent = false; + private boolean mUserInputEnabled = true; + private @OffscreenPageLimit int mOffscreenPageLimit = OFFSCREEN_PAGE_LIMIT_DEFAULT; + AccessibilityProvider mAccessibilityProvider; // to avoid creation of a synthetic accessor + + public ViewPager2(@NonNull Context context) { + super(context); + initialize(context, null); + } + + public ViewPager2(@NonNull Context context, @Nullable AttributeSet attrs) { + super(context, attrs); + initialize(context, attrs); + } + + public ViewPager2(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) { + super(context, attrs, defStyleAttr); + initialize(context, attrs); + } + + @RequiresApi(21) + public ViewPager2(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, + int defStyleRes) { + super(context, attrs, defStyleAttr, defStyleRes); + initialize(context, attrs); + } + + private void initialize(Context context, AttributeSet attrs) { + mAccessibilityProvider = new BasicAccessibilityProvider(); + + mRecyclerView = new RecyclerViewImpl(context); + mRecyclerView.setId(ViewCompat.generateViewId()); + mRecyclerView.setDescendantFocusability(FOCUS_BEFORE_DESCENDANTS); + + mLayoutManager = new LinearLayoutManagerImpl(context); + mRecyclerView.setLayoutManager(mLayoutManager); + mRecyclerView.setScrollingTouchSlop(RecyclerView.TOUCH_SLOP_PAGING); + setOrientation(context, attrs); + + mRecyclerView.setLayoutParams( + new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); + mRecyclerView.addOnChildAttachStateChangeListener(enforceChildFillListener()); + + // Create ScrollEventAdapter before attaching PagerSnapHelper to RecyclerView, because the + // attach process calls PagerSnapHelperImpl.findSnapView, which uses the mScrollEventAdapter + mScrollEventAdapter = new ScrollEventAdapter(this); + // Create FakeDrag before attaching PagerSnapHelper, same reason as above + mFakeDragger = new FakeDrag(this, mScrollEventAdapter, mRecyclerView); + mPagerSnapHelper = new PagerSnapHelperImpl(); + mPagerSnapHelper.attachToRecyclerView(mRecyclerView); + // Add mScrollEventAdapter after attaching mPagerSnapHelper to mRecyclerView, because we + // don't want to respond on the events sent out during the attach process + mRecyclerView.addOnScrollListener(mScrollEventAdapter); + + mPageChangeEventDispatcher = new CompositeOnPageChangeCallback(3); + mScrollEventAdapter.setOnPageChangeCallback(mPageChangeEventDispatcher); + + // Callback that updates mCurrentItem after swipes. Also triggered in other cases, but in + // all those cases mCurrentItem will only be overwritten with the same value. + final OnPageChangeCallback currentItemUpdater = new OnPageChangeCallback() { + @Override + public void onPageSelected(int position) { + if (mCurrentItem != position) { + mCurrentItem = position; + mAccessibilityProvider.onSetNewCurrentItem(); + } + } + + @Override + public void onPageScrollStateChanged(int newState) { + if (newState == SCROLL_STATE_IDLE) { + updateCurrentItem(); + } + } + }; + + // Prevents focus from remaining on a no-longer visible page + final OnPageChangeCallback focusClearer = new OnPageChangeCallback() { + @Override + public void onPageSelected(int position) { + clearFocus(); + if (hasFocus()) { // if clear focus did not succeed + mRecyclerView.requestFocus(View.FOCUS_FORWARD); + } + } + }; + + // Add currentItemUpdater before mExternalPageChangeCallbacks, because we need to update + // internal state first + mPageChangeEventDispatcher.addOnPageChangeCallback(currentItemUpdater); + mPageChangeEventDispatcher.addOnPageChangeCallback(focusClearer); + // Allow a11y to register its listeners after currentItemUpdater (so it has the + // right data). TODO: replace ordering comments with a test. + mAccessibilityProvider.onInitialize(mPageChangeEventDispatcher, mRecyclerView); + mPageChangeEventDispatcher.addOnPageChangeCallback(mExternalPageChangeCallbacks); + + // Add mPageTransformerAdapter after mExternalPageChangeCallbacks, because page transform + // events must be fired after scroll events + mPageTransformerAdapter = new PageTransformerAdapter(mLayoutManager); + mPageChangeEventDispatcher.addOnPageChangeCallback(mPageTransformerAdapter); + + attachViewToParent(mRecyclerView, 0, mRecyclerView.getLayoutParams()); + } + + /** + * A lot of places in code rely on an assumption that the page fills the whole ViewPager2. + * + * TODO(b/70666617) Allow page width different than width/height 100%/100% + */ + private RecyclerView.OnChildAttachStateChangeListener enforceChildFillListener() { + return new RecyclerView.OnChildAttachStateChangeListener() { + @Override + public void onChildViewAttachedToWindow(@NonNull View view) { + RecyclerView.LayoutParams layoutParams = + (RecyclerView.LayoutParams) view.getLayoutParams(); + if (layoutParams.width != LayoutParams.MATCH_PARENT + || layoutParams.height != LayoutParams.MATCH_PARENT) { + throw new IllegalStateException( + "Pages must fill the whole ViewPager2 (use match_parent)"); + } + } + + @Override + public void onChildViewDetachedFromWindow(@NonNull View view) { + // nothing + } + }; + } + + @RequiresApi(23) + @Override + public CharSequence getAccessibilityClassName() { + if (mAccessibilityProvider.handlesGetAccessibilityClassName()) { + return mAccessibilityProvider.onGetAccessibilityClassName(); + } + return super.getAccessibilityClassName(); + } + + private void setOrientation(Context context, AttributeSet attrs) { + TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ViewPager2); + if (Build.VERSION.SDK_INT >= 29) { + saveAttributeDataForStyleable(context, R.styleable.ViewPager2, attrs, a, 0, 0); + } + try { + setOrientation( + a.getInt(R.styleable.ViewPager2_android_orientation, ORIENTATION_HORIZONTAL)); + } finally { + a.recycle(); + } + } + + @SuppressWarnings("ConstantConditions") + @Nullable + @Override + protected Parcelable onSaveInstanceState() { + Parcelable superState = super.onSaveInstanceState(); + SavedState ss = new SavedState(superState); + + ss.mRecyclerViewId = mRecyclerView.getId(); + ss.mCurrentItem = mPendingCurrentItem == NO_POSITION ? mCurrentItem : mPendingCurrentItem; + + if (mPendingAdapterState != null) { + ss.mAdapterState = mPendingAdapterState; + } else { + RecyclerView.Adapter adapter = mRecyclerView.getAdapter(); + if (adapter instanceof StatefulAdapter) { + ss.mAdapterState = ((StatefulAdapter) adapter).saveState(); + } + } + + return ss; + } + + @Override + protected void onRestoreInstanceState(Parcelable state) { + if (!(state instanceof SavedState)) { + super.onRestoreInstanceState(state); + return; + } + + SavedState ss = (SavedState) state; + super.onRestoreInstanceState(ss.getSuperState()); + mPendingCurrentItem = ss.mCurrentItem; + mPendingAdapterState = ss.mAdapterState; + } + + private void restorePendingState() { + if (mPendingCurrentItem == NO_POSITION) { + // No state to restore, or state is already restored + return; + } + RecyclerView.Adapter adapter = getAdapter(); + if (adapter == null) { + return; + } + if (mPendingAdapterState != null) { + if (adapter instanceof StatefulAdapter) { + ((StatefulAdapter) adapter).restoreState(mPendingAdapterState); + } + mPendingAdapterState = null; + } + // Now we have an adapter, we can clamp the pending current item and set it + mCurrentItem = Math.max(0, Math.min(mPendingCurrentItem, adapter.getItemCount() - 1)); + mPendingCurrentItem = NO_POSITION; + mRecyclerView.scrollToPosition(mCurrentItem); + mAccessibilityProvider.onRestorePendingState(); + } + + @Override + protected void dispatchRestoreInstanceState(SparseArray container) { + // RecyclerView changed an id, so we need to reflect that in the saved state + Parcelable state = container.get(getId()); + if (state instanceof SavedState) { + final int previousRvId = ((SavedState) state).mRecyclerViewId; + final int currentRvId = mRecyclerView.getId(); + container.put(currentRvId, container.get(previousRvId)); + container.remove(previousRvId); + } + + super.dispatchRestoreInstanceState(container); + + // State of ViewPager2 and its child (RecyclerView) has been restored now + restorePendingState(); + } + + static class SavedState extends BaseSavedState { + int mRecyclerViewId; + int mCurrentItem; + Parcelable mAdapterState; + + @RequiresApi(24) + SavedState(Parcel source, ClassLoader loader) { + super(source, loader); + readValues(source, loader); + } + + SavedState(Parcel source) { + super(source); + readValues(source, null); + } + + SavedState(Parcelable superState) { + super(superState); + } + + private void readValues(Parcel source, ClassLoader loader) { + mRecyclerViewId = source.readInt(); + mCurrentItem = source.readInt(); + mAdapterState = source.readParcelable(loader); + } + + @Override + public void writeToParcel(Parcel out, int flags) { + super.writeToParcel(out, flags); + out.writeInt(mRecyclerViewId); + out.writeInt(mCurrentItem); + out.writeParcelable(mAdapterState, flags); + } + + public static final Creator CREATOR = new ClassLoaderCreator() { + @Override + public SavedState createFromParcel(Parcel source, ClassLoader loader) { + return Build.VERSION.SDK_INT >= 24 + ? new SavedState(source, loader) + : new SavedState(source); + } + + @Override + public SavedState createFromParcel(Parcel source) { + return createFromParcel(source, null); + } + + @Override + public SavedState[] newArray(int size) { + return new SavedState[size]; + } + }; + } + + /** + *

Set a new adapter to provide page views on demand.

+ * + *

If you're planning to use {@link androidx.fragment.app.Fragment Fragments} as pages, + * implement {@link androidx.viewpager2.adapter.FragmentStateAdapter FragmentStateAdapter}. If + * your pages are Views, implement {@link RecyclerView.Adapter} as usual.

+ * + *

If your pages contain LayoutTransitions, then those LayoutTransitions must have + * {@code animateParentHierarchy} set to {@code false}. Note that if you have a ViewGroup with + * {@code animateLayoutChanges="true"} in your layout xml file, a LayoutTransition is added + * automatically to that ViewGroup. You will need to manually call {@link + * android.animation.LayoutTransition#setAnimateParentHierarchy(boolean) + * getLayoutTransition().setAnimateParentHierarchy(false)} on that ViewGroup after you inflated + * the xml layout, like this:

+ * + *
+     * View view = layoutInflater.inflate(R.layout.page, parent, false);
+     * ViewGroup viewGroup = view.findViewById(R.id.animated_viewgroup);
+     * viewGroup.getLayoutTransition().setAnimateParentHierarchy(false);
+     * 
+ * + * @param adapter The adapter to use, or {@code null} to remove the current adapter + * @see androidx.viewpager2.adapter.FragmentStateAdapter + * @see RecyclerView#setAdapter(Adapter) + */ + public void setAdapter(@Nullable @SuppressWarnings("rawtypes") RecyclerView.Adapter adapter) { + final RecyclerView.Adapter currentAdapter = mRecyclerView.getAdapter(); + mAccessibilityProvider.onDetachAdapter(currentAdapter); + unregisterCurrentItemDataSetTracker(currentAdapter); + mRecyclerView.setAdapter(adapter); + mCurrentItem = 0; + restorePendingState(); + mAccessibilityProvider.onAttachAdapter(adapter); + registerCurrentItemDataSetTracker(adapter); + } + + private void registerCurrentItemDataSetTracker(@Nullable RecyclerView.Adapter adapter) { + if (adapter != null) { + adapter.registerAdapterDataObserver(mCurrentItemDataSetChangeObserver); + } + } + + private void unregisterCurrentItemDataSetTracker(@Nullable RecyclerView.Adapter adapter) { + if (adapter != null) { + adapter.unregisterAdapterDataObserver(mCurrentItemDataSetChangeObserver); + } + } + + @SuppressWarnings("rawtypes") + public @Nullable + RecyclerView.Adapter getAdapter() { + return mRecyclerView.getAdapter(); + } + + @Override + public void onViewAdded(View child) { + // TODO(b/70666620): consider adding a support for Decor views + throw new IllegalStateException( + getClass().getSimpleName() + " does not support direct child views"); + } + + @Override + protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + // TODO(b/70666622): consider margin support + // TODO(b/70666626): consider delegating all this to RecyclerView + // TODO(b/70666625): write automated tests for this + + measureChild(mRecyclerView, widthMeasureSpec, heightMeasureSpec); + int width = mRecyclerView.getMeasuredWidth(); + int height = mRecyclerView.getMeasuredHeight(); + int childState = mRecyclerView.getMeasuredState(); + + width += getPaddingLeft() + getPaddingRight(); + height += getPaddingTop() + getPaddingBottom(); + + width = Math.max(width, getSuggestedMinimumWidth()); + height = Math.max(height, getSuggestedMinimumHeight()); + + setMeasuredDimension(resolveSizeAndState(width, widthMeasureSpec, childState), + resolveSizeAndState(height, heightMeasureSpec, + childState << MEASURED_HEIGHT_STATE_SHIFT)); + } + + @Override + protected void onLayout(boolean changed, int l, int t, int r, int b) { + int width = mRecyclerView.getMeasuredWidth(); + int height = mRecyclerView.getMeasuredHeight(); + + // TODO(b/70666626): consider delegating padding handling to the RecyclerView to avoid + // an unnatural page transition effect: http://shortn/_Vnug3yZpQT + mTmpContainerRect.left = getPaddingLeft(); + mTmpContainerRect.right = r - l - getPaddingRight(); + mTmpContainerRect.top = getPaddingTop(); + mTmpContainerRect.bottom = b - t - getPaddingBottom(); + + Gravity.apply(Gravity.TOP | Gravity.START, width, height, mTmpContainerRect, mTmpChildRect); + mRecyclerView.layout(mTmpChildRect.left, mTmpChildRect.top, mTmpChildRect.right, + mTmpChildRect.bottom); + + if (mCurrentItemDirty) { + updateCurrentItem(); + } + } + + /** Updates {@link #mCurrentItem} based on what is currently visible in the viewport. */ + void updateCurrentItem() { + if (mPagerSnapHelper == null) { + throw new IllegalStateException("Design assumption violated."); + } + + View snapView = mPagerSnapHelper.findSnapView(mLayoutManager); + if (snapView == null) { + return; // nothing we can do + } + int snapPosition = mLayoutManager.getPosition(snapView); + + if (snapPosition != mCurrentItem && getScrollState() == SCROLL_STATE_IDLE) { + /** TODO: revisit if push to {@link ScrollEventAdapter} / separate component */ + mPageChangeEventDispatcher.onPageSelected(snapPosition); + } + + mCurrentItemDirty = false; + } + + int getPageSize() { + final RecyclerView rv = mRecyclerView; + return getOrientation() == ORIENTATION_HORIZONTAL + ? rv.getWidth() - rv.getPaddingLeft() - rv.getPaddingRight() + : rv.getHeight() - rv.getPaddingTop() - rv.getPaddingBottom(); + } + + /** + * Sets the orientation of the ViewPager2. + * + * @param orientation {@link #ORIENTATION_HORIZONTAL} or {@link #ORIENTATION_VERTICAL} + */ + public void setOrientation(@Orientation int orientation) { + mLayoutManager.setOrientation(orientation); + mAccessibilityProvider.onSetOrientation(); + } + + public @Orientation int getOrientation() { + return mLayoutManager.getOrientation(); + } + + boolean isRtl() { + return mLayoutManager.getLayoutDirection() == ViewCompat.LAYOUT_DIRECTION_RTL; + } + + /** + * Set the currently selected page. If the ViewPager has already been through its first + * layout with its current adapter there will be a smooth animated transition between + * the current item and the specified item. Silently ignored if the adapter is not set or + * empty. Clamps item to the bounds of the adapter. + * + * TODO(b/123069219): verify first layout behavior + * + * @param item Item index to select + */ + public void setCurrentItem(int item) { + setCurrentItem(item, true); + } + + /** + * Set the currently selected page. If {@code smoothScroll = true}, will perform a smooth + * animation from the current item to the new item. Silently ignored if the adapter is not set + * or empty. Clamps item to the bounds of the adapter. + * + * @param item Item index to select + * @param smoothScroll True to smoothly scroll to the new item, false to transition immediately + */ + public void setCurrentItem(int item, boolean smoothScroll) { + if (isFakeDragging()) { + throw new IllegalStateException("Cannot change current item when ViewPager2 is fake " + + "dragging"); + } + setCurrentItemInternal(item, smoothScroll); + } + + void setCurrentItemInternal(int item, boolean smoothScroll) { + + // 1. Preprocessing (check state, validate item, decide if update is necessary, etc) + + RecyclerView.Adapter adapter = getAdapter(); + if (adapter == null) { + // Update the pending current item if we're still waiting for the adapter + if (mPendingCurrentItem != NO_POSITION) { + mPendingCurrentItem = Math.max(item, 0); + } + return; + } + if (adapter.getItemCount() <= 0) { + // Adapter is empty + return; + } + item = Math.max(item, 0); + item = Math.min(item, adapter.getItemCount() - 1); + + if (item == mCurrentItem && mScrollEventAdapter.isIdle()) { + // Already at the correct page + return; + } + if (item == mCurrentItem && smoothScroll) { + // Already scrolling to the correct page, but not yet there. Only handle instant scrolls + // because then we need to interrupt the current smooth scroll. + return; + } + + // 2. Update the item internally + + double previousItem = mCurrentItem; + mCurrentItem = item; + mAccessibilityProvider.onSetNewCurrentItem(); + + if (!mScrollEventAdapter.isIdle()) { + // Scroll in progress, overwrite previousItem with actual current position + previousItem = mScrollEventAdapter.getRelativeScrollPosition(); + } + + // 3. Perform the necessary scroll actions on RecyclerView + + mScrollEventAdapter.notifyProgrammaticScroll(item, smoothScroll); + if (!smoothScroll) { + mRecyclerView.scrollToPosition(item); + return; + } + + // For smooth scroll, pre-jump to nearby item for long jumps. + if (Math.abs(item - previousItem) > 3) { + mRecyclerView.scrollToPosition(item > previousItem ? item - 3 : item + 3); + // TODO(b/114361680): call smoothScrollToPosition synchronously (blocked by b/114019007) + mRecyclerView.post(new SmoothScrollToPosition(item, mRecyclerView)); + } else { + mRecyclerView.smoothScrollToPosition(item); + } + } + + /** + * Returns the currently selected page. If no page can sensibly be selected because there is no + * adapter or the adapter is empty, returns 0. + * + * @return Currently selected page + */ + public int getCurrentItem() { + return mCurrentItem; + } + + /** + * Returns the current scroll state of the ViewPager2. Returned value is one of can be one of + * {@link #SCROLL_STATE_IDLE}, {@link #SCROLL_STATE_DRAGGING} or {@link #SCROLL_STATE_SETTLING}. + * + * @return The scroll state that was last dispatched to {@link + * OnPageChangeCallback#onPageScrollStateChanged(int)} + */ + @ScrollState + public int getScrollState() { + return mScrollEventAdapter.getScrollState(); + } + + /** + * Start a fake drag of the pager. + * + *

A fake drag can be useful if you want to synchronize the motion of the ViewPager2 with the + * touch scrolling of another view, while still letting the ViewPager2 control the snapping + * motion and fling behavior. (e.g. parallax-scrolling tabs.) Call {@link #fakeDragBy(float)} to + * simulate the actual drag motion. Call {@link #endFakeDrag()} to complete the fake drag and + * fling as necessary. + * + *

A fake drag can be interrupted by a real drag. From that point on, all calls to {@code + * fakeDragBy} and {@code endFakeDrag} will be ignored until the next fake drag is started by + * calling {@code beginFakeDrag}. If you need the ViewPager2 to ignore touch events and other + * user input during a fake drag, use {@link #setUserInputEnabled(boolean)}. If a real or fake + * drag is already in progress, this method will return {@code false}. + * + * @return {@code true} if the fake drag began successfully, {@code false} if it could not be + * started + * + * @see #fakeDragBy(float) + * @see #endFakeDrag() + * @see #isFakeDragging() + */ + public boolean beginFakeDrag() { + return mFakeDragger.beginFakeDrag(); + } + + /** + * Fake drag by an offset in pixels. You must have called {@link #beginFakeDrag()} first. Drag + * happens in the direction of the orientation. Positive offsets will drag to the previous page, + * negative values to the next page, with one exception: if layout direction is set to RTL and + * the ViewPager2's orientation is horizontal, then the behavior will be inverted. This matches + * the deltas of touch events that would cause the same real drag. + * + *

If the pager is not in the fake dragging state anymore, it ignores this call and returns + * {@code false}. + * + * @param offsetPxFloat Offset in pixels to drag by + * @return {@code true} if the fake drag was executed. If {@code false} is returned, it means + * there was no fake drag to end. + * + * @see #beginFakeDrag() + * @see #endFakeDrag() + * @see #isFakeDragging() + */ + public boolean fakeDragBy(@SuppressLint("SupportAnnotationUsage") @Px float offsetPxFloat) { + return mFakeDragger.fakeDragBy(offsetPxFloat); + } + + /** + * End a fake drag of the pager. + * + * @return {@code true} if the fake drag was ended. If {@code false} is returned, it means there + * was no fake drag to end. + * + * @see #beginFakeDrag() + * @see #fakeDragBy(float) + * @see #isFakeDragging() + */ + public boolean endFakeDrag() { + return mFakeDragger.endFakeDrag(); + } + + /** + * Returns {@code true} if a fake drag is in progress. + * + * @return {@code true} if currently in a fake drag, {@code false} otherwise. + * @see #beginFakeDrag() + * @see #fakeDragBy(float) + * @see #endFakeDrag() + */ + public boolean isFakeDragging() { + return mFakeDragger.isFakeDragging(); + } + + /** + * Snaps the ViewPager2 to the closest page + */ + void snapToPage() { + // Method copied from PagerSnapHelper#snapToTargetExistingView + // When fixing something here, make sure to update that method as well + View view = mPagerSnapHelper.findSnapView(mLayoutManager); + if (view == null) { + return; + } + int[] snapDistance = mPagerSnapHelper.calculateDistanceToFinalSnap(mLayoutManager, view); + //noinspection ConstantConditions + if (snapDistance[0] != 0 || snapDistance[1] != 0) { + mRecyclerView.smoothScrollBy(snapDistance[0], snapDistance[1]); + } + } + + /** + * Enable or disable user initiated scrolling. This includes touch input (scroll and fling + * gestures) and accessibility input. Disabling keyboard input is not yet supported. When user + * initiated scrolling is disabled, programmatic scrolls through {@link #setCurrentItem(int, + * boolean) setCurrentItem} still work. By default, user initiated scrolling is enabled. + * + * @param enabled {@code true} to allow user initiated scrolling, {@code false} to block user + * initiated scrolling + * @see #isUserInputEnabled() + */ + public void setUserInputEnabled(boolean enabled) { + mUserInputEnabled = enabled; + mAccessibilityProvider.onSetUserInputEnabled(); + } + + /** + * Returns if user initiated scrolling between pages is enabled. Enabled by default. + * + * @return {@code true} if users can scroll the ViewPager2, {@code false} otherwise + * @see #setUserInputEnabled(boolean) + */ + public boolean isUserInputEnabled() { + return mUserInputEnabled; + } + + /** + *

Set the number of pages that should be retained to either side of the currently visible + * page(s). Pages beyond this limit will be recreated from the adapter when needed. Set this to + * {@link #OFFSCREEN_PAGE_LIMIT_DEFAULT} to use RecyclerView's caching strategy. The given value + * must either be larger than 0, or {@code #OFFSCREEN_PAGE_LIMIT_DEFAULT}.

+ * + *

Pages within {@code limit} pages away from the current page are created and added to the + * view hierarchy, even though they are not visible on the screen. Pages outside this limit will + * be removed from the view hierarchy, but the {@code ViewHolder}s will be recycled as usual by + * {@link RecyclerView}.

+ * + *

This is offered as an optimization. If you know in advance the number of pages you will + * need to support or have lazy-loading mechanisms in place on your pages, tweaking this setting + * can have benefits in perceived smoothness of paging animations and interaction. If you have a + * small number of pages (3-4) that you can keep active all at once, less time will be spent in + * layout for newly created view subtrees as the user pages back and forth.

+ * + *

You should keep this limit low, especially if your pages have complex layouts. By default + * it is set to {@code OFFSCREEN_PAGE_LIMIT_DEFAULT}.

+ * + * @param limit How many pages will be kept offscreen on either side. Valid values are all + * values {@code >= 1} and {@link #OFFSCREEN_PAGE_LIMIT_DEFAULT} + * @throws IllegalArgumentException If the given limit is invalid + * @see #getOffscreenPageLimit() + */ + public void setOffscreenPageLimit(@OffscreenPageLimit int limit) { + if (limit < 1 && limit != OFFSCREEN_PAGE_LIMIT_DEFAULT) { + throw new IllegalArgumentException( + "Offscreen page limit must be OFFSCREEN_PAGE_LIMIT_DEFAULT or a number > 0"); + } + mOffscreenPageLimit = limit; + // Trigger layout so prefetch happens through getExtraLayoutSize() + mRecyclerView.requestLayout(); + } + + /** + * Returns the number of pages that will be retained to either side of the current page in the + * view hierarchy in an idle state. Defaults to {@link #OFFSCREEN_PAGE_LIMIT_DEFAULT}. + * + * @return How many pages will be kept offscreen on either side + * @see #setOffscreenPageLimit(int) + */ + @OffscreenPageLimit + public int getOffscreenPageLimit() { + return mOffscreenPageLimit; + } + + @Override + public boolean canScrollHorizontally(int direction) { + return mRecyclerView.canScrollHorizontally(direction); + } + + @Override + public boolean canScrollVertically(int direction) { + return mRecyclerView.canScrollVertically(direction); + } + + /** + * Add a callback that will be invoked whenever the page changes or is incrementally + * scrolled. See {@link OnPageChangeCallback}. + * + *

Components that add a callback should take care to remove it when finished. + * + * @param callback callback to add + */ + public void registerOnPageChangeCallback(@NonNull OnPageChangeCallback callback) { + mExternalPageChangeCallbacks.addOnPageChangeCallback(callback); + } + + /** + * Remove a callback that was previously added via + * {@link #registerOnPageChangeCallback(OnPageChangeCallback)}. + * + * @param callback callback to remove + */ + public void unregisterOnPageChangeCallback(@NonNull OnPageChangeCallback callback) { + mExternalPageChangeCallbacks.removeOnPageChangeCallback(callback); + } + + /** + * Sets a {@link PageTransformer} that will be called for each attached page whenever the + * scroll position is changed. This allows the application to apply custom property + * transformations to each page, overriding the default sliding behavior. + *

+ * Note: setting a {@link PageTransformer} disables data-set change animations to prevent + * conflicts between the two animation systems. Setting a {@code null} transformer will restore + * data-set change animations. + * + * @param transformer PageTransformer that will modify each page's animation properties + * + * @see MarginPageTransformer + * @see CompositePageTransformer + */ + public void setPageTransformer(@Nullable PageTransformer transformer) { + if (transformer != null) { + if (!mSavedItemAnimatorPresent) { + mSavedItemAnimator = mRecyclerView.getItemAnimator(); + mSavedItemAnimatorPresent = true; + } + mRecyclerView.setItemAnimator(null); + } else { + if (mSavedItemAnimatorPresent) { + mRecyclerView.setItemAnimator(mSavedItemAnimator); + mSavedItemAnimator = null; + mSavedItemAnimatorPresent = false; + } + } + + // TODO: add support for reverseDrawingOrder: b/112892792 + // TODO: add support for pageLayerType: b/112893074 + if (transformer == mPageTransformerAdapter.getPageTransformer()) { + return; + } + mPageTransformerAdapter.setPageTransformer(transformer); + requestTransform(); + } + + /** + * Trigger a call to the registered {@link PageTransformer PageTransformer}'s {@link + * PageTransformer#transformPage(View, float) transformPage} method. Call this when something + * has changed which has invalidated the transformations defined by the {@code PageTransformer} + * that did not trigger a page scroll. + */ + public void requestTransform() { + if (mPageTransformerAdapter.getPageTransformer() == null) { + return; + } + double relativePosition = mScrollEventAdapter.getRelativeScrollPosition(); + int position = (int) relativePosition; + float positionOffset = (float) (relativePosition - position); + int positionOffsetPx = Math.round(getPageSize() * positionOffset); + mPageTransformerAdapter.onPageScrolled(position, positionOffset, positionOffsetPx); + } + + @Override + @RequiresApi(17) + public void setLayoutDirection(int layoutDirection) { + super.setLayoutDirection(layoutDirection); + mAccessibilityProvider.onSetLayoutDirection(); + } + + @Override + public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { + super.onInitializeAccessibilityNodeInfo(info); + mAccessibilityProvider.onInitializeAccessibilityNodeInfo(info); + } + + @RequiresApi(16) + @Override + public boolean performAccessibilityAction(int action, Bundle arguments) { + if (mAccessibilityProvider.handlesPerformAccessibilityAction(action, arguments)) { + return mAccessibilityProvider.onPerformAccessibilityAction(action, arguments); + } + return super.performAccessibilityAction(action, arguments); + } + + /** + * Slightly modified RecyclerView to get ViewPager behavior in accessibility and to + * enable/disable user scrolling. + */ + private class RecyclerViewImpl extends RecyclerView { + RecyclerViewImpl(@NonNull Context context) { + super(context); + } + + @RequiresApi(23) + @Override + public CharSequence getAccessibilityClassName() { + if (mAccessibilityProvider.handlesRvGetAccessibilityClassName()) { + return mAccessibilityProvider.onRvGetAccessibilityClassName(); + } + return super.getAccessibilityClassName(); + } + + @Override + public void onInitializeAccessibilityEvent(@NonNull AccessibilityEvent event) { + super.onInitializeAccessibilityEvent(event); + event.setFromIndex(mCurrentItem); + event.setToIndex(mCurrentItem); + mAccessibilityProvider.onRvInitializeAccessibilityEvent(event); + } + + @SuppressLint("ClickableViewAccessibility") + @Override + public boolean onTouchEvent(MotionEvent event) { + return isUserInputEnabled() && super.onTouchEvent(event); + } + + @Override + public boolean onInterceptTouchEvent(MotionEvent ev) { + return isUserInputEnabled() && super.onInterceptTouchEvent(ev); + } + } + + private class LinearLayoutManagerImpl extends ViewPager2LinearLayoutManager { + LinearLayoutManagerImpl(Context context) { + super(context); + } + + @Override + public boolean performAccessibilityAction(@NonNull RecyclerView.Recycler recycler, + @NonNull RecyclerView.State state, int action, @Nullable Bundle args) { + if (mAccessibilityProvider.handlesLmPerformAccessibilityAction(action)) { + return mAccessibilityProvider.onLmPerformAccessibilityAction(action); + } + return super.performAccessibilityAction(recycler, state, action, args); + } + + @Override + public void onInitializeAccessibilityNodeInfo(@NonNull RecyclerView.Recycler recycler, + @NonNull RecyclerView.State state, @NonNull AccessibilityNodeInfoCompat info) { + super.onInitializeAccessibilityNodeInfo(recycler, state, info); + mAccessibilityProvider.onLmInitializeAccessibilityNodeInfo(info); + } + + @Override + protected void calculateExtraLayoutSpace(@NonNull RecyclerView.State state, + @NonNull int[] extraLayoutSpace) { + int pageLimit = getOffscreenPageLimit(); + if (pageLimit == OFFSCREEN_PAGE_LIMIT_DEFAULT) { + // Only do custom prefetching of offscreen pages if requested + super.calculateExtraLayoutSpace(state, extraLayoutSpace); + return; + } + final int offscreenSpace = getPageSize() * pageLimit; + extraLayoutSpace[0] = offscreenSpace; + extraLayoutSpace[1] = offscreenSpace; + } + + @Override + public boolean requestChildRectangleOnScreen(@NonNull RecyclerView parent, + @NonNull View child, @NonNull Rect rect, boolean immediate, + boolean focusedChildVisible) { + return false; // users should use setCurrentItem instead + } + } + + private class PagerSnapHelperImpl extends PagerSnapHelper { + PagerSnapHelperImpl() { + } + + @Nullable + @Override + public View findSnapView(RecyclerView.LayoutManager layoutManager) { + // When interrupting a smooth scroll with a fake drag, we stop RecyclerView's scroll + // animation, which fires a scroll state change to IDLE. PagerSnapHelper then kicks in + // to snap to a page, which we need to prevent here. + // Simplifying that case: during a fake drag, no snapping should occur. + return isFakeDragging() ? null : super.findSnapView(layoutManager); + } + } + + private static class SmoothScrollToPosition implements Runnable { + private final int mPosition; + private final RecyclerView mRecyclerView; + + SmoothScrollToPosition(int position, RecyclerView recyclerView) { + mPosition = position; + mRecyclerView = recyclerView; // to avoid a synthetic accessor + } + + @Override + public void run() { + mRecyclerView.smoothScrollToPosition(mPosition); + } + } + + /** + * Callback interface for responding to changing state of the selected page. + */ + public abstract static class OnPageChangeCallback { + /** + * This method will be invoked when the current page is scrolled, either as part + * of a programmatically initiated smooth scroll or a user initiated touch scroll. + * + * @param position Position index of the first page currently being displayed. + * Page position+1 will be visible if positionOffset is nonzero. + * @param positionOffset Value from [0, 1) indicating the offset from the page at position. + * @param positionOffsetPixels Value in pixels indicating the offset from position. + */ + public void onPageScrolled(int position, float positionOffset, + @Px int positionOffsetPixels) { + } + + /** + * This method will be invoked when a new page becomes selected. Animation is not + * necessarily complete. + * + * @param position Position index of the new selected page. + */ + public void onPageSelected(int position) { + } + + /** + * Called when the scroll state changes. Useful for discovering when the user begins + * dragging, when a fake drag is started, when the pager is automatically settling to the + * current page, or when it is fully stopped/idle. {@code state} can be one of {@link + * #SCROLL_STATE_IDLE}, {@link #SCROLL_STATE_DRAGGING} or {@link #SCROLL_STATE_SETTLING}. + */ + public void onPageScrollStateChanged(@ScrollState int state) { + } + } + + /** + * A PageTransformer is invoked whenever a visible/attached page is scrolled. + * This offers an opportunity for the application to apply a custom transformation + * to the page views using animation properties. + */ + public interface PageTransformer { + + /** + * Apply a property transformation to the given page. + * + * @param page Apply the transformation to this page + * @param position Position of page relative to the current front-and-center + * position of the pager. 0 is front and center. 1 is one full + * page position to the right, and -2 is two pages to the left. + * Minimum / maximum observed values depend on how many pages we keep + * attached, which depends on offscreenPageLimit. + * + * @see #setOffscreenPageLimit(int) + */ + void transformPage(@NonNull View page, float position); + } + + /** + * Add an {@link ItemDecoration} to this ViewPager2. Item decorations can + * affect both measurement and drawing of individual item views. + * + *

Item decorations are ordered. Decorations placed earlier in the list will + * be run/queried/drawn first for their effects on item views. Padding added to views + * will be nested; a padding added by an earlier decoration will mean further + * item decorations in the list will be asked to draw/pad within the previous decoration's + * given area.

+ * + * @param decor Decoration to add + */ + public void addItemDecoration(@NonNull RecyclerView.ItemDecoration decor) { + mRecyclerView.addItemDecoration(decor); + } + + /** + * Add an {@link ItemDecoration} to this ViewPager2. Item decorations can + * affect both measurement and drawing of individual item views. + * + *

Item decorations are ordered. Decorations placed earlier in the list will + * be run/queried/drawn first for their effects on item views. Padding added to views + * will be nested; a padding added by an earlier decoration will mean further + * item decorations in the list will be asked to draw/pad within the previous decoration's + * given area.

+ * + * @param decor Decoration to add + * @param index Position in the decoration chain to insert this decoration at. If this value + * is negative the decoration will be added at the end. + * @throws IndexOutOfBoundsException on indexes larger than {@link #getItemDecorationCount} + */ + public void addItemDecoration(@NonNull RecyclerView.ItemDecoration decor, int index) { + mRecyclerView.addItemDecoration(decor, index); + } + + /** + * Returns an {@link ItemDecoration} previously added to this ViewPager2. + * + * @param index The index position of the desired ItemDecoration. + * @return the ItemDecoration at index position + * @throws IndexOutOfBoundsException on invalid index + */ + @NonNull + public RecyclerView.ItemDecoration getItemDecorationAt(int index) { + return mRecyclerView.getItemDecorationAt(index); + } + + /** + * Returns the number of {@link ItemDecoration} currently added to this ViewPager2. + * + * @return number of ItemDecorations currently added added to this ViewPager2. + */ + public int getItemDecorationCount() { + return mRecyclerView.getItemDecorationCount(); + } + + /** + * Invalidates all ItemDecorations. If ViewPager2 has item decorations, calling this method + * will trigger a {@link #requestLayout()} call. + */ + public void invalidateItemDecorations() { + mRecyclerView.invalidateItemDecorations(); + } + + /** + * Removes the {@link ItemDecoration} associated with the supplied index position. + * + * @param index The index position of the ItemDecoration to be removed. + * @throws IndexOutOfBoundsException on invalid index + */ + public void removeItemDecorationAt(int index) { + mRecyclerView.removeItemDecorationAt(index); + } + + /** + * Remove an {@link ItemDecoration} from this ViewPager2. + * + *

The given decoration will no longer impact the measurement and drawing of + * item views.

+ * + * @param decor Decoration to remove + * @see #addItemDecoration(ItemDecoration) + */ + public void removeItemDecoration(@NonNull RecyclerView.ItemDecoration decor) { + mRecyclerView.removeItemDecoration(decor); + } + + // TODO(b/141956012): Suppressed during upgrade to AGP 3.6. + @SuppressWarnings("ClassCanBeStatic") + private abstract class AccessibilityProvider { + void onInitialize(@NonNull CompositeOnPageChangeCallback pageChangeEventDispatcher, + @NonNull RecyclerView recyclerView) { + } + + boolean handlesGetAccessibilityClassName() { + return false; + } + + String onGetAccessibilityClassName() { + throw new IllegalStateException("Not implemented."); + } + + void onRestorePendingState() { + } + + void onAttachAdapter(@Nullable RecyclerView.Adapter newAdapter) { + } + + void onDetachAdapter(@Nullable RecyclerView.Adapter oldAdapter) { + } + + void onSetOrientation() { + } + + void onSetNewCurrentItem() { + } + + void onSetUserInputEnabled() { + } + + void onSetLayoutDirection() { + } + + void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { + } + + boolean handlesPerformAccessibilityAction(int action, Bundle arguments) { + return false; + } + + boolean onPerformAccessibilityAction(int action, Bundle arguments) { + throw new IllegalStateException("Not implemented."); + } + + void onRvInitializeAccessibilityEvent(@NonNull AccessibilityEvent event) { + } + + boolean handlesLmPerformAccessibilityAction(int action) { + return false; + } + + boolean onLmPerformAccessibilityAction(int action) { + throw new IllegalStateException("Not implemented."); + } + + void onLmInitializeAccessibilityNodeInfo(@NonNull AccessibilityNodeInfoCompat info) { + } + + boolean handlesRvGetAccessibilityClassName() { + return false; + } + + CharSequence onRvGetAccessibilityClassName() { + throw new IllegalStateException("Not implemented."); + } + } + + class BasicAccessibilityProvider extends AccessibilityProvider { + @Override + public boolean handlesLmPerformAccessibilityAction(int action) { + return (action == AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD + || action == AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD) + && !isUserInputEnabled(); + } + + @Override + public boolean onLmPerformAccessibilityAction(int action) { + if (!handlesLmPerformAccessibilityAction(action)) { + throw new IllegalStateException(); + } + return false; + } + + @Override + public void onLmInitializeAccessibilityNodeInfo( + @NonNull AccessibilityNodeInfoCompat info) { + if (!isUserInputEnabled()) { + info.removeAction(AccessibilityNodeInfoCompat.AccessibilityActionCompat.ACTION_SCROLL_BACKWARD); + info.removeAction(AccessibilityNodeInfoCompat.AccessibilityActionCompat.ACTION_SCROLL_FORWARD); + info.setScrollable(false); + } + } + + @Override + public boolean handlesRvGetAccessibilityClassName() { + return true; + } + + @Override + public CharSequence onRvGetAccessibilityClassName() { + if (!handlesRvGetAccessibilityClassName()) { + throw new IllegalStateException(); + } + return "androidx.viewpager.widget.ViewPager"; + } + } + + + /** + * Simplified {@link RecyclerView.AdapterDataObserver} for clients interested in any data-set + * changes regardless of their nature. + */ + private abstract static class DataSetChangeObserver extends RecyclerView.AdapterDataObserver { + @Override + public abstract void onChanged(); + + @Override + public final void onItemRangeChanged(int positionStart, int itemCount) { + onChanged(); + } + + @Override + public final void onItemRangeChanged(int positionStart, int itemCount, + @Nullable Object payload) { + onChanged(); + } + + @Override + public final void onItemRangeInserted(int positionStart, int itemCount) { + onChanged(); + } + + @Override + public final void onItemRangeRemoved(int positionStart, int itemCount) { + onChanged(); + } + + @Override + public final void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) { + onChanged(); + } + } +} + diff --git a/viewpager2/src/main/res/values/values.xml b/viewpager2/src/main/res/values/values.xml new file mode 100644 index 0000000..5170984 --- /dev/null +++ b/viewpager2/src/main/res/values/values.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/viewpager2/src/test/java/com/vinsonguo/viewpager2/ExampleUnitTest.kt b/viewpager2/src/test/java/com/vinsonguo/viewpager2/ExampleUnitTest.kt new file mode 100644 index 0000000..bebbf63 --- /dev/null +++ b/viewpager2/src/test/java/com/vinsonguo/viewpager2/ExampleUnitTest.kt @@ -0,0 +1,17 @@ +package com.vinsonguo.viewpager2 + +import org.junit.Test + +import org.junit.Assert.* + +/** + * Example local unit test, which will execute on the development machine (host). + * + * See [testing documentation](http://d.android.com/tools/testing). + */ +class ExampleUnitTest { + @Test + fun addition_isCorrect() { + assertEquals(4, 2 + 2) + } +} \ No newline at end of file