Repository: NightlyNexus/ViewStatePagerAdapter Branch: master Commit: ee35f709f8a1 Files: 27 Total size: 45.5 KB Directory structure: gitextract_3oak_3gv/ ├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── LICENSE.txt ├── README.md ├── RELEASING.md ├── build.gradle ├── checkstyle.xml ├── gradle/ │ ├── gradle-mvn-push.gradle │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── settings.gradle ├── viewstatepageradapter/ │ ├── build.gradle │ ├── gradle.properties │ └── src/ │ └── main/ │ ├── AndroidManifest.xml │ └── java/ │ └── com/ │ └── nightlynexus/ │ └── viewstatepageradapter/ │ └── ViewStatePagerAdapter.java └── viewstatepageradapter-sample/ ├── build.gradle └── src/ └── main/ ├── AndroidManifest.xml ├── java/ │ └── com/ │ └── nightlynexus/ │ └── viewstatepageradaptersample/ │ ├── ViewPagerActivity.java │ └── ViewPagerAdapter.java └── res/ ├── layout/ │ ├── page_bottom.xml │ ├── page_top.xml │ └── pagers.xml └── values/ ├── dimens.xml └── strings.xml ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ # IntelliJ IDEA .idea *.iml # Gradle .gradle gradlew.bat build local.properties lint-reports # Mac OS .DS_Store ================================================ FILE: .travis.yml ================================================ language: android jdk: - oraclejdk8 before_install: # Install SDK license so Android Gradle plugin can install deps. - mkdir "$ANDROID_HOME/licenses" || true - echo "24333f8a63b6825ea9c5514f83c2829b004d1fee" > "$ANDROID_HOME/licenses/android-sdk-license" # Install the rest of tools (e.g., avdmanager). - sdkmanager tools # Install the system image. - sdkmanager "system-images;android-19;default;armeabi-v7a" # Create and start emulator for the script. Meant to race the install task. - echo no | avdmanager create avd --force -n test -k "system-images;android-19;default;armeabi-v7a" - $ANDROID_HOME/emulator/emulator -avd test -no-audio -no-window & install: ./gradlew clean assemble --stacktrace before_script: - android-wait-for-emulator - adb shell settings put global window_animation_scale 0 & - adb shell settings put global transition_animation_scale 0 & - adb shell settings put global animator_duration_scale 0 & - adb shell input keyevent 82 & script: ./gradlew check connectedCheck --stacktrace env: global: - ADB_INSTALL_TIMEOUT=8 notifications: email: false sudo: false cache: directories: - $HOME/.gradle ================================================ FILE: CHANGELOG.md ================================================ Change Log ========== Version 1.1.0 *(2019-03-02)* ---------------------------- * New: Update to androidx. Version 1.0.4 *(2017-01-07)* ---------------------------- * New: Update to support v4 split to reduce method count. Version 1.0.3 *(2016-08-04)* ---------------------------- * New: Expose the SavedState final type via `saveState()`. Version 1.0.2 *(2016-06-11)* ---------------------------- * Fix: Revert last fix. The wrong Parcelable being restored is always a consumer error, as far as has been observed. Version 1.0.1 *(2016-06-05)* ---------------------------- * Fix: Fail silently with wrong restored Parcelable. Version 1.0.0 *(2016-06-04)* ---------------------------- * Initial version. ================================================ FILE: LICENSE.txt ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] 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. ================================================ FILE: README.md ================================================ ViewStatePagerAdapter ===================== Saves and restores View states in ViewPagers. [`ViewStatePagerAdapter`](viewstatepageradapter/src/main/java/com/nightlynexus/viewstatepageradapter/ViewStatePagerAdapter.java) is simply an implementation of `androidx.viewpager.widget.PagerAdapter` and automatically saves and restores View states when returning to pages (previously removed Views in the ViewPager) and after ViewPager's state restoration. `ViewStatePagerAdapter` is similar to [`androidx.fragment.app.FragmentStatePagerAdapter`](https://developer.android.com/reference/androidx/fragment/app/FragmentStatePagerAdapter/) but for use with just Views, rather than Fragments. ### Sample The sample application shows the difference between the use of a `ViewStatePagerAdapter` and a `ViewPagerAdapter` (with no saving and restoring of View state). ![](images/sample.gif) Download -------- Gradle: ```groovy compile 'com.nightlynexus.viewstatepageradapter:viewstatepageradapter:1.1.0' ``` License -------- Copyright 2016 Eric Cochran 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. ================================================ FILE: RELEASING.md ================================================ Releasing ======== 1. Change the version in `gradle.properties` to a non-SNAPSHOT version. 2. Update the `CHANGELOG.md` for the impending release. 3. Update the `README.md` with the new version. 4. `git commit -am "Prepare for release X.Y.Z."` (where X.Y.Z is the new version) 5. `./gradlew clean uploadArchives`. 6. Visit [Sonatype Nexus](https://oss.sonatype.org/) and promote the artifact. 7. `git tag -a X.Y.X -m "Version X.Y.Z"` (where X.Y.Z is the new version) 8. Update the `gradle.properties` to the next SNAPSHOT version. 9. `git commit -am "Prepare next development version."` 10. `git push && git push --tags` If step 5 or 6 fails, drop the Sonatype repo, fix the problem, commit, and start again at step 5. ================================================ FILE: build.gradle ================================================ buildscript { dependencies { classpath 'com.android.tools.build:gradle:3.3.1' classpath 'net.ltgt.gradle:gradle-errorprone-plugin:0.0.16' } repositories { google() mavenCentral() maven { url 'https://plugins.gradle.org/m2/' } } } allprojects { tasks.withType(JavaCompile) { options.compilerArgs += ['-Xlint:all', '-Xlint:-deprecation', '-Werror'] } apply plugin: 'net.ltgt.errorprone' apply plugin: 'checkstyle' repositories { google() jcenter() // Needed for Lint. } dependencies { errorprone 'com.google.errorprone:error_prone_core:2.3.3' } task checkstyle(type: Checkstyle) { configFile rootProject.file('checkstyle.xml') source 'src' include '**/*.java' exclude '**/gen/**' classpath = files() } checkstyle { toolVersion = '7.7' } } ================================================ FILE: checkstyle.xml ================================================ ================================================ FILE: gradle/gradle-mvn-push.gradle ================================================ /* * Copyright 2013 Chris Banes * * 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. */ apply plugin: 'maven' apply plugin: 'signing' def isReleaseBuild() { return VERSION_NAME.contains("SNAPSHOT") == false } def getRepositoryUsername() { return hasProperty('SONATYPE_NEXUS_USERNAME') ? SONATYPE_NEXUS_USERNAME : "" } def getRepositoryPassword() { return hasProperty('SONATYPE_NEXUS_PASSWORD') ? SONATYPE_NEXUS_PASSWORD : "" } afterEvaluate { project -> uploadArchives { repositories { mavenDeployer { beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) } pom.groupId = GROUP pom.artifactId = POM_ARTIFACT_ID pom.version = VERSION_NAME repository(url: "https://oss.sonatype.org/service/local/staging/deploy/maven2/") { authentication(userName: getRepositoryUsername(), password: getRepositoryPassword()) } snapshotRepository(url: "https://oss.sonatype.org/content/repositories/snapshots/") { authentication(userName: getRepositoryUsername(), password: getRepositoryPassword()) } pom.project { name POM_NAME packaging POM_PACKAGING description POM_DESCRIPTION url POM_URL scm { url POM_SCM_URL connection POM_SCM_CONNECTION developerConnection POM_SCM_DEV_CONNECTION } licenses { license { name POM_LICENCE_NAME url POM_LICENCE_URL distribution POM_LICENCE_DIST } } developers { developer { id POM_DEVELOPER_ID name POM_DEVELOPER_NAME } } } } } } signing { required { isReleaseBuild() && gradle.taskGraph.hasTask("uploadArchives") } sign configurations.archives } task androidJavadocs(type: Javadoc) { source = android.sourceSets.main.java.srcDirs classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) if (JavaVersion.current().isJava8Compatible()) { allprojects { tasks.withType(Javadoc) { options.addStringOption('Xdoclint:none', '-quiet') } } } } task androidJavadocsJar(type: Jar, dependsOn: androidJavadocs) { classifier = 'javadoc' from androidJavadocs.destinationDir } task androidSourcesJar(type: Jar) { classifier = 'sources' from android.sourceSets.main.java.sourceFiles } artifacts { archives androidSourcesJar archives androidJavadocsJar } } ================================================ FILE: gradle/wrapper/gradle-wrapper.properties ================================================ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-5.2.1-all.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists ================================================ FILE: gradle.properties ================================================ VERSION_NAME=1.1.0 GROUP=com.nightlynexus.viewstatepageradapter POM_DESCRIPTION=Saves and restores View states in ViewPagers. POM_URL=https://github.com/NightlyNexus/ViewStatePagerAdapter/ POM_SCM_URL=https://github.com/NightlyNexus/ViewStatePagerAdapter/ POM_SCM_CONNECTION=scm:git@github.com/NightlyNexus/ViewStatePagerAdapter.git POM_SCM_DEV_CONNECTION=scm:git@github.com:NightlyNexus/ViewStatePagerAdapter.git POM_LICENCE_NAME=The Apache Software License, Version 2.0 POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt POM_LICENCE_DIST=repo POM_DEVELOPER_ID=NightlyNexus POM_DEVELOPER_NAME=Eric Cochran ================================================ FILE: gradlew ================================================ #!/usr/bin/env sh ############################################################################## ## ## 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"' # 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, switch paths to Windows format before running java if $cygwin ; 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=$((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" # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then cd "$(dirname "$0")" fi exec "$JAVACMD" "$@" ================================================ FILE: settings.gradle ================================================ include ':viewstatepageradapter', ':viewstatepageradapter-sample' ================================================ FILE: viewstatepageradapter/build.gradle ================================================ apply plugin: 'com.android.library' apply from: rootProject.file('gradle/gradle-mvn-push.gradle') android { compileSdkVersion 28 defaultConfig { minSdkVersion 15 } lintOptions { abortOnError true warningsAsErrors true textReport true textOutput 'stdout' htmlReport true htmlOutput rootProject.file("lint-reports/${name}.html") } // TODO: Replace with https://issuetracker.google.com/issues/72050365 once released. libraryVariants.all { it.generateBuildConfig.enabled = false } } dependencies { api 'androidx.viewpager:viewpager:1.0.0' } ================================================ FILE: viewstatepageradapter/gradle.properties ================================================ POM_NAME=ViewStatePagerAdapter POM_ARTIFACT_ID=viewstatepageradapter POM_PACKAGING=aar ================================================ FILE: viewstatepageradapter/src/main/AndroidManifest.xml ================================================ ================================================ FILE: viewstatepageradapter/src/main/java/com/nightlynexus/viewstatepageradapter/ViewStatePagerAdapter.java ================================================ /* * Copyright (C) 2016 Eric Cochran * * 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. */ package com.nightlynexus.viewstatepageradapter; import android.os.Parcel; import android.os.Parcelable; import android.util.SparseArray; import android.view.View; import android.view.ViewGroup; import androidx.viewpager.widget.PagerAdapter; public abstract class ViewStatePagerAdapter extends PagerAdapter { private final SparseArray attached; private SparseArray> detached; public ViewStatePagerAdapter() { this(3); } /** * @param capacity the initial capacity of the collection of attached Views. */ public ViewStatePagerAdapter(int capacity) { attached = new SparseArray<>(capacity); } protected abstract View createView(ViewGroup container, int position); protected void destroyView(ViewGroup container, int position, View view) { } @Override public final SavedState saveState() { for (int i = 0, size = attached.size(); i < size; i++) { int position = attached.keyAt(i); View view = attached.valueAt(i); putInDetached(position, view); } return new SavedState(detached); } @Override public final void restoreState(Parcelable state, ClassLoader loader) { SavedState savedState = (SavedState) state; detached = savedState.detached; } @Override public final Object instantiateItem(ViewGroup container, int position) { if (detached == null) { detached = new SparseArray<>(); } View view = createView(container, position); if (view == null) { throw new NullPointerException( "createView must not return null. (position: " + position + ")"); } SparseArray viewState = detached.get(position); if (viewState != null) { view.restoreHierarchyState(viewState); } container.addView(view); attached.put(position, view); return view; } @Override public final void destroyItem(ViewGroup container, int position, Object object) { View view = (View) object; destroyView(container, position, view); putInDetached(position, view); container.removeView(view); attached.remove(position); } private void putInDetached(int position, View view) { SparseArray viewState = new SparseArray<>(); view.saveHierarchyState(viewState); detached.put(position, viewState); } @Override public final Object instantiateItem(View container, int position) { throw new UnsupportedOperationException(); } @Override public final void destroyItem(View container, int position, Object object) { throw new UnsupportedOperationException(); } @Override public final boolean isViewFromObject(View view, Object object) { return view == object; } public static final class SavedState implements Parcelable { final SparseArray> detached; SavedState(SparseArray> detached) { this.detached = detached; } @Override public void writeToParcel(Parcel dest, int flags) { writeNestedSparseArray(dest, detached, flags); } public static final Creator CREATOR = new Creator() { @Override public SavedState createFromParcel(Parcel in) { SparseArray> detached = readNestedSparseArray(in, SavedState.class.getClassLoader()); return new SavedState(detached); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; @Override public int describeContents() { return 0; } static SparseArray> readNestedSparseArray(Parcel in, ClassLoader loader) { int size = in.readInt(); if (size == -1) { return null; } SparseArray> map = new SparseArray<>(size); while (size != 0) { int key = in.readInt(); SparseArray value = readSparseArray(in, loader); map.append(key, value); size--; } return map; } static SparseArray readSparseArray(Parcel in, ClassLoader loader) { int size = in.readInt(); if (size == -1) { return null; } SparseArray map = new SparseArray<>(size); while (size != 0) { int key = in.readInt(); Parcelable value = in.readParcelable(loader); map.append(key, value); size--; } return map; } static void writeNestedSparseArray(Parcel dest, SparseArray> map, int flags) { if (map == null) { dest.writeInt(-1); return; } int size = map.size(); dest.writeInt(size); int i = 0; while (i != size) { dest.writeInt(map.keyAt(i)); writeSparseArray(dest, map.valueAt(i), flags); i++; } } static void writeSparseArray(Parcel dest, SparseArray map, int flags) { if (map == null) { dest.writeInt(-1); return; } int size = map.size(); dest.writeInt(size); int i = 0; while (i != size) { dest.writeInt(map.keyAt(i)); dest.writeParcelable(map.valueAt(i), flags); i++; } } } } ================================================ FILE: viewstatepageradapter-sample/build.gradle ================================================ apply plugin: 'com.android.application' android { compileSdkVersion 28 defaultConfig { applicationId "com.nightlynexus.viewstatepageradaptersample" minSdkVersion 15 targetSdkVersion 28 versionCode 1 versionName "1.0" } lintOptions { abortOnError true // warningsAsErrors true textReport true textOutput 'stdout' htmlReport true htmlOutput rootProject.file("lint-reports/${name}.html") } } dependencies { implementation project(':viewstatepageradapter') } ================================================ FILE: viewstatepageradapter-sample/src/main/AndroidManifest.xml ================================================ ================================================ FILE: viewstatepageradapter-sample/src/main/java/com/nightlynexus/viewstatepageradaptersample/ViewPagerActivity.java ================================================ package com.nightlynexus.viewstatepageradaptersample; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.viewpager.widget.ViewPager; import com.nightlynexus.viewstatepageradapter.ViewStatePagerAdapter; public final class ViewPagerActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.pagers); ViewPager withState = findViewById(R.id.with_state); ViewPager withoutState = findViewById(R.id.without_state); withState.setAdapter(new SampleEditTextViewStatePagerAdapter(withState.getContext())); withoutState.setAdapter(new SampleEditTextViewPagerAdapter(withoutState.getContext())); } private static final class SampleEditTextViewStatePagerAdapter extends ViewStatePagerAdapter { private final Context context; SampleEditTextViewStatePagerAdapter(Context context) { this.context = context; } @SuppressLint("SetTextI18n") @Override protected View createView(ViewGroup container, int position) { View view = LayoutInflater.from(context).inflate(R.layout.page_top, container, false); TextView pagerNumber = view.findViewById(R.id.page_number); pagerNumber.setText(Integer.toString(position)); return view; } @Override public int getCount() { return 10; } } private static final class SampleEditTextViewPagerAdapter extends ViewPagerAdapter { private final Context context; SampleEditTextViewPagerAdapter(Context context) { this.context = context; } @SuppressLint("SetTextI18n") @Override protected View createView(ViewGroup container, int position) { View view = LayoutInflater.from(context).inflate(R.layout.page_bottom, container, false); TextView pagerNumber = view.findViewById(R.id.page_number); pagerNumber.setText(Integer.toString(position)); return view; } @Override public int getCount() { return 10; } } } ================================================ FILE: viewstatepageradapter-sample/src/main/java/com/nightlynexus/viewstatepageradaptersample/ViewPagerAdapter.java ================================================ package com.nightlynexus.viewstatepageradaptersample; import android.view.View; import android.view.ViewGroup; import androidx.viewpager.widget.PagerAdapter; abstract class ViewPagerAdapter extends PagerAdapter { protected abstract View createView(ViewGroup container, int position); protected void destroyView(ViewGroup container, int position, View view) { } @Override public final Object instantiateItem(ViewGroup container, int position) { View view = createView(container, position); if (view == null) { throw new NullPointerException( "createView must not return null. (position: " + position + ")"); } container.addView(view); return view; } @Override public final void destroyItem(ViewGroup container, int position, Object object) { View view = (View) object; destroyView(container, position, view); container.removeView(view); } @Override public final Object instantiateItem(View container, int position) { throw new UnsupportedOperationException(); } @Override public final void destroyItem(View container, int position, Object object) { throw new UnsupportedOperationException(); } @Override public final boolean isViewFromObject(View view, Object object) { return view == object; } } ================================================ FILE: viewstatepageradapter-sample/src/main/res/layout/page_bottom.xml ================================================ ================================================ FILE: viewstatepageradapter-sample/src/main/res/layout/page_top.xml ================================================ ================================================ FILE: viewstatepageradapter-sample/src/main/res/layout/pagers.xml ================================================ ================================================ FILE: viewstatepageradapter-sample/src/main/res/values/dimens.xml ================================================ 16dp 16sp 32dp 24sp 32sp ================================================ FILE: viewstatepageradapter-sample/src/main/res/values/strings.xml ================================================ ViewStatePagerAdapter Sample With State Without State