Repository: KeepSafe/MultiStateAnimation Branch: master Commit: 7dbd2d19437a Files: 30 Total size: 84.0 KB Directory structure: gitextract_u5l7ysds/ ├── .gitignore ├── LICENSE.txt ├── README.md ├── build.gradle ├── gradle/ │ ├── gradle-mvn-push.gradle │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat ├── library/ │ ├── .gitignore │ ├── AndroidManifest.xml │ ├── build.gradle │ ├── gradle.properties │ └── src/ │ └── main/ │ └── java/ │ └── com/ │ └── getkeepsafe/ │ └── android/ │ └── multistateanimation/ │ ├── MultiStateAnimation.java │ └── NotifyingAnimationDrawable.java ├── samples/ │ ├── .gitignore │ ├── AndroidManifest.xml │ ├── build.gradle │ ├── res/ │ │ ├── layout/ │ │ │ └── activity_three_state_sample.xml │ │ ├── menu/ │ │ │ └── menu_three_state_sample.xml │ │ ├── raw/ │ │ │ └── sample_animation.json │ │ ├── values/ │ │ │ ├── colors.xml │ │ │ ├── dimens.xml │ │ │ ├── strings.xml │ │ │ └── styles.xml │ │ └── values-w820dp/ │ │ └── dimens.xml │ └── src/ │ └── main/ │ └── java/ │ └── com/ │ └── getkeepsafe/ │ └── android/ │ └── multistateanimation/ │ └── samples/ │ └── ThreeStateSampleActivity.java ├── scripts/ │ └── generate_animation_json.py └── settings.gradle ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ bin/ gen/ build/ local.properties Thumbs.db .DS_Store .idea .gradle *.iml ================================================ 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 ================================================ # MultiStateAnimation Android library to create complex multi-state animations. ![Demo animation](docs/images/demo_1.gif) ## Overview A class that allows for complex multi-state animations using Android's `AnimationDrawable`. It supports both oneshot and looped animation sections. Transitions between sections can be defined, and will play automatically when moving between the defined states. State transitions can be queued asynchronously, and the library will take car of smoothly starting the next animation once the current section is complete. ## Installation Add the following dependency to your gradle build file: ```gradle dependencies { compile 'com.getkeepsafe.android.multistateanimation:library:1.1.1' } ``` ## Usage Each animation consists of a series of states. A state has some metadata and a list of frames to draw. A state can also define transitions from other states. A transition is a list of frames that will be played when moving directly from a specified state to the state where the transition is defined. An animation can be defined either with a JSON file included as a `raw` resource, or directly in Java code using builders. ### Defining an animation with Java code ```java // The ID is used in code to specify a section to play MultiStateAnimation.SectionBuilder firstSection = new MultiStateAnimation.SectionBuilder("first_section") // If true, this section will play once and stop. Otherwise it // will loop indefinitely. .setOneshot(false) // The number of milliseconds that each frame of this section will // play .setFrameDuration(33) // Each frame is the name of an image resource. They will be // played in the order added. .addFrame(R.drawable.first_section_01) .addFrame(R.drawable.first_section_02); // The frames of a transition will be played before playing // the normal frames of this section when transitioning. In // this case, the frames for this transition will play if // "first_section" is playing when queueTransition("second_section") // is called MultiStateAnimation.TransitionBuilder transitionFromFirst = new MultiStateAnimation.TransitionBuilder() .setFrameDuration(33) .addFrame(R.drawable.first_to_second_transition_001) .addFrame(R.drawable.first_to_second_transition_002) .addFrame(R.drawable.first_to_second_transition_003); // As a special case, a transition ID of "" is a transition // from nothing. It will play if the associated section is the // first to ever play. MultiStateAnimation.TransitionBuilder transitionFromNothing = new MultiStateAnimation.TransitionBuilder() .addFrame(R.drawable.nothing_to_second_001) .addFrame(R.drawable.nothing_to_second_002); // A section with a single frame and "oneshot" set to true is // equivalent to a static image MultiStateAnimation.SectionBuilder secondSection = new MultiStateAnimation.SectionBuilder("second_section") .setOneshot(true) .addTransition("first_section", transitionFromFirst) .addTransition("", transitionFromNothing) .addFrame(R.drawable.second_section_01); // Animation should be given an View that will be used to display the animation. ImageView view = (ImageView) findViewById(R.id.animationImageView); MultiStateAnimation animation = new MultiStateAnimation.Builder(view) .addSection(startSection) .addSection(loadingSection) .addSection(endSection) .build(context); ``` ### Defining an animation using JSON As an alternative to using Java code, you can instead define animations using a JSON file stored as a raw resource. The following JSON file defines the same animation as the above Java code. ```javascript { "first_section": { "oneshot": false, "frame_duration": 33, "frames": [ "first_section_1", "first_section_2" ], } "second_section": { "oneshot": true, "frames": [ "second_section_01" ], "transitions_from": { "first_section": { "frame_duration": 33, "frames": [ "first_to_second_transition_001", "first_to_second_transition_002", "first_to_second_transition_003" ] } "": { "frames": [ "nothing_to_second_001", "nothing_to_second_002" ] } } } } ``` Then a `MultiStateAnimationOjbect` can be created in Java: ```java ImageView view = (ImageView) findViewById(R.id.animationImageView); MultiStateAnimation animationSeries = MultiStateAnimation.fromJsonResource(context, view, R.raw.sample_animation); ``` #### Generating JSON animation files automatically Included in the repo is a [Python 3 script](scripts/generate_animation_json.py) that can assist in generating the JSON for an animation. To use it, place the frames for each section of the animation in a separate folder, the pass those folders to the script. For example, to generate the JSON file above, create a folder structure like this: ```bash . ├── first_section │   ├── first_section_1.png │   └── first_section_2.png ├── first_to_second_transition │   ├── first_to_second_transition_001.png │   ├── first_to_second_transition_002.png │   └── first_to_second_transition_003.png ├── nothing_to_second_transition │   ├── nothing_to_second_001.png │   └── nothing_to_second_002.png └── second_section └── second_section_01.png ``` These folders can be located anywhere in your filesystem. To generate the JSON file, run the script with the folders as arguments: ```bash python generate_animation_json.py first_section/ second_section/ first_to_second_transition/ nothing_to_second_transition/ --output=sample_animation.json ``` The script will ask a series of questions about each section, and save the resulting json file to `sample_animation.json`. You can run `python generate_animation_json.py --help` to see a full list of arguments ### Playing animations Once the animation object is created via one of the above methods, you can use `queueTransition` and `transitionNow` from the GUI thread to start playing the animations. ```java animationSeries.queueTransition("first_section"); ``` ## Sample application See the [main Activity](samples/src/main/java/com/getkeepsafe/android/multistateanimation/samples/ThreeStateSampleActivity.java) and the [json animation definition](samples/res/raw/sample_animation.json) in the [sample application](samples/) for an example. ## Java API Check out [the Javadocs](http://keepsafe.github.io/MultiStateAnimation/) for more API details. ## License Copyright 2016 KeepSafe Inc. 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: build.gradle ================================================ buildscript { repositories { mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:1.2.3' } } allprojects { repositories { mavenCentral() } } ================================================ 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 getReleaseRepositoryUrl() { return hasProperty('RELEASE_REPOSITORY_URL') ? RELEASE_REPOSITORY_URL : "https://oss.sonatype.org/service/local/staging/deploy/maven2/" } def getSnapshotRepositoryUrl() { return hasProperty('SNAPSHOT_REPOSITORY_URL') ? SNAPSHOT_REPOSITORY_URL : "https://oss.sonatype.org/content/repositories/snapshots/" } def getRepositoryUsername() { return hasProperty('NEXUS_USERNAME') ? NEXUS_USERNAME : "" } def getRepositoryPassword() { return hasProperty('NEXUS_PASSWORD') ? 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: getReleaseRepositoryUrl()) { authentication(userName: getRepositoryUsername(), password: getRepositoryPassword()) } snapshotRepository(url: getSnapshotRepositoryUrl()) { 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)) } 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 ================================================ #Wed Apr 10 15:27:10 PDT 2013 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-all.zip ================================================ FILE: gradle.properties ================================================ VERSION_NAME=1.1.1 VERSION_CODE=3 GROUP=com.getkeepsafe.android.multistateanimation POM_ARTIFACT_ID=MultiStateAnimation POM_NAME=MultiStateAnimation POM_PACKAGING=aar POM_DESCRIPTION=An Android library to create complex animations. POM_INCEPTION_YEAR=2015 POM_URL=https://github.com/KeepSafe/MultiStateAnimation POM_SCM_URL=https://github.com/KeepSafe/MultiStateAnimation POM_SCM_CONNECTION=scm:git:git://github.com/KeepSafe/MultiStateAnimation.git POM_SCM_DEV_CONNECTION=scm:git:git@github.com:KeepSafe/MultiStateAnimation.git POM_LICENCE_NAME=Apache License 2.0 POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt POM_LICENCE_DIST=repo POM_DEVELOPER_ID=keepsafe POM_DEVELOPER_NAME=KeepSafe Software, Inc. ================================================ FILE: gradlew ================================================ #!/usr/bin/env bash ############################################################################## ## ## Gradle start up script for UN*X ## ############################################################################## # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS="" APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` # 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 case "`uname`" in CYGWIN* ) cygwin=true ;; Darwin* ) darwin=true ;; MINGW* ) msys=true ;; esac # For Cygwin, ensure paths are in UNIX format before anything is touched. if $cygwin ; then [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` fi # 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\"`/" >&- APP_HOME="`pwd -P`" cd "$SAVED" >&- 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" ] ; 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"` # 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 # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules function splitJvmOpts() { JVM_OPTS=("$@") } eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" ================================================ FILE: gradlew.bat ================================================ @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 @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= set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @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 init 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 init 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 :init @rem Get command-line arguments, handling Windowz variants if not "%OS%" == "Windows_NT" goto win9xME_args if "%@eval[2+2]" == "4" goto 4NT_args :win9xME_args @rem Slurp the command line arguments. set CMD_LINE_ARGS= set _SKIP=2 :win9xME_args_slurp if "x%~1" == "x" goto execute set CMD_LINE_ARGS=%* goto execute :4NT_args @rem Get arguments from the 4NT Shell from JP Software set CMD_LINE_ARGS=%$ :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 %CMD_LINE_ARGS% :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 ================================================ FILE: library/.gitignore ================================================ /build ================================================ FILE: library/AndroidManifest.xml ================================================ ================================================ FILE: library/build.gradle ================================================ apply plugin: 'com.android.library' group = GROUP version = VERSION_NAME repositories { mavenCentral() } android { compileSdkVersion 22 buildToolsVersion '22.0.1' defaultConfig { minSdkVersion 1 targetSdkVersion 22 versionCode 3 versionName '1.1.1' } sourceSets { main { manifest.srcFile 'AndroidManifest.xml' res.srcDirs = ['res'] } } lintOptions { abortOnError false } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) } android.libraryVariants.all { variant -> task("generate${variant.name.capitalize()}Javadoc", type: Javadoc) { // title = '' // description = '' source = variant.javaCompile.source classpath = files(variant.javaCompile.classpath.files, project.android.getBootClasspath()) options { links "http://docs.oracle.com/javase/7/docs/api/" linksOffline "http://d.android.com/reference","${android.sdkDirectory}/docs/reference" } exclude '**/BuildConfig.java' exclude '**/R.java' } } apply from: file('../gradle/gradle-mvn-push.gradle') ================================================ FILE: library/gradle.properties ================================================ POM_NAME=MultiStateAnimation POM_ARTIFACT_ID=library POM_PACKAGING=aar ================================================ FILE: library/src/main/java/com/getkeepsafe/android/multistateanimation/MultiStateAnimation.java ================================================ package com.getkeepsafe.android.multistateanimation; import android.annotation.TargetApi; import android.content.Context; import android.graphics.drawable.AnimationDrawable; import android.os.Build; import android.view.View; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Animates a series of separate AnimationDrawables on the background of a single View. * The view to animate is passed in the constructor. Animations are added with addSection, or they * can be defined in a JSON resource and passed to fromJsonResource. To start an animation, * call transitionNow or queueTransition. * * @author AJ Alt */ public class MultiStateAnimation implements NotifyingAnimationDrawable.OnAnimationFinishedListener { public static final int DEFAULT_FRAME_DURATION = 33; public static final boolean DEFAULT_ONESHOT_STATUS = true; /** * Cache to prevent duplicate json reads; map of resource id -> builder. */ private static final Map mBuilderCache = new HashMap<>(); /** * A class that creates an AnimationDrawable from a list of frames. */ private static class AnimationDrawableLoader { private int mFrameDuration; private boolean mIsOneShot; private int[] mFrameIds; private Context mContext; public AnimationDrawableLoader(Context context) { mContext = context; } public AnimationDrawableLoader(Context context, int frameDuration, boolean isOneShot, String[] frameNames) { mContext = context; mFrameDuration = frameDuration; mIsOneShot = isOneShot; mFrameIds = new int[frameNames.length]; for (int i = 0; i < frameNames.length; i++) { mFrameIds[i] = getDrawableResourceId(mContext, frameNames[i]); } } public AnimationDrawableLoader(Context context, int frameDuration, boolean isOneShot, int[] frameIds) { mContext = context; mFrameDuration = frameDuration; mIsOneShot = isOneShot; mFrameIds = frameIds; } public NotifyingAnimationDrawable load() { NotifyingAnimationDrawable d = new NotifyingAnimationDrawable(); d.setOneShot(mIsOneShot); // XXX: AnimationDrawable has a bug that causes it to be unresponsive // if exactly one frame is added. A workaround is to add the same frame // twice if there's only one. if (mFrameIds.length == 1) { for (int i = 0; i < 2; i++) { d.addFrame(mContext.getResources().getDrawable(mFrameIds[0]), mFrameDuration); } d.setOneShot(true); } else { for (int resid : mFrameIds) { d.addFrame(mContext.getResources().getDrawable(resid), mFrameDuration); } } return d; } /** * Returns the duration of this animation. * * @return int number of milliseconds that the animation will play. */ public int totalDuration() { return mFrameDuration * mFrameIds.length; } } /** * A class that holds loaders for a single animation section and transitions to that section. */ private static class AnimationSection { private String mId; private AnimationDrawableLoader mLoader; private Map mTransitions; public AnimationSection(String id, AnimationDrawableLoader loader, Map transitions) { mId = id; mLoader = loader; mTransitions = transitions; } /** * @param id The id of this section. * @param loader A loader for this section's primary animation. */ public AnimationSection(String id, AnimationDrawableLoader loader) { this(id, loader, new HashMap()); } public String getId() { return mId; } /** * Creates the primary animation drawable for this section. */ public NotifyingAnimationDrawable loadDrawable() { return mLoader.load(); } /** * @param fromId The id of the section to transition from. * @return The transition animation for fromId if one has been added, or null. */ public NotifyingAnimationDrawable getTransition(String fromId) { if (mTransitions.containsKey(fromId)) { return mTransitions.get(fromId).load(); } return null; } /** * @param fromId The Id of the section that will be transitioned from. * @param loader The loader for this transition animation. */ public void addTransition(String fromId, AnimationDrawableLoader loader) { mTransitions.put(fromId, loader); } /** * Calculates the total duration if the animation, including the transition. * * @param fromId If a transition exists from this id, the duration will include the transition duration. * @return int number of milliseconds. */ public int getDuration(String fromId) { int total = mLoader.totalDuration(); AnimationDrawableLoader loader = mTransitions.get(fromId); if (loader != null) { total += loader.totalDuration(); } return total; } /** * Calculates the duration of the animation, excluding any transition. * * @return int number of milliseconds. */ public int getDuration() { return getDuration(null); } } public interface AnimationSeriesListener { /** * Called when a playing animation finishes and before the drawable is replaced. */ void onAnimationFinished(); /** * Called after a new animation has been created, but before the animation has started. * The new animation can be accessed through getCurrentDrawable. */ void onAnimationStarting(); } private WeakReference mListener = new WeakReference(null); private AnimationSection mCurrentSection; /** * The id of the animation that will be started as soon as the current animation * finishes, or null if no animation is queued. */ private String mQueuedSectionId; private NotifyingAnimationDrawable mCurrentDrawable; /** * The id of the previous section if a transition is currently playing, or null * id no transition is playing. */ private String mTransitioningFromId; private View mView; /** * An array of resource IDs corresponding to animations that can be played. */ private Map mSectionsById; /** * Create a new instance and automatically set animations as the background of the given view. * * @param view If not null, animations will be set as the background of this view. */ public MultiStateAnimation(View view) { mSectionsById = new HashMap<>(); mView = view; } /** * Create an instance without giving a view to hold the animations. *

* Note that due to a limitation in AnimationDrawable, you must set * created animations as the image or background of a View in an * onAnimationStarting listener, otherwise the animation will not * advance. * * @see com.getkeepsafe.android.multistateanimation.MultiStateAnimation.AnimationSeriesListener#onAnimationStarting() */ public MultiStateAnimation() { this(null); } /** * Load the id for a drawable resource from its name */ private static int getDrawableResourceId(Context context, String name) { return context.getResources().getIdentifier(name, "drawable", context.getPackageName()); } /** * Convert a JSONArray containing only strings to a String[]. * * @param jsonArray the array to convert. * @return a String[] with the contents of the JSONArray. * @throws org.json.JSONException */ private static String[] jsonArrayToArray(JSONArray jsonArray) throws JSONException { String[] array = new String[jsonArray.length()]; for (int i = 0; i < array.length; i++) { array[i] = jsonArray.getString(i); } return array; } /** * Convert a List of Integers to an int[] * * @param list the List to convert * @return an int[] with the same values as the list */ private static int[] integerListToArray(List list) { int[] array = new int[list.size()]; for (int i = 0; i < list.size(); i++) { array[i] = list.get(i); } return array; } /** * A Builder for a transition from one section to another. *

* It's possible to use the same transition between more than one set of sections. */ public static class TransitionBuilder { private List mFrames = new ArrayList<>(); private int mFrameDuration = DEFAULT_FRAME_DURATION; /** * Add a frame to the transition animation. * * @param imageResource The resource id of a image drawable. * @return This Builder object to allow for chaining of calls to set methods */ public TransitionBuilder addFrame(int imageResource) { mFrames.add(imageResource); return this; } /** * Set the duration that each frame in this section will play. * * @param frameDuration The number of milliseconds that each frame will be displayed. * @return This Builder object to allow for chaining of calls to set methods */ public TransitionBuilder setFrameDuration(int frameDuration) { mFrameDuration = frameDuration; return this; } private AnimationDrawableLoader build(Context context) { return new AnimationDrawableLoader(context, mFrameDuration, true, integerListToArray(mFrames)); } } /** * A builder for an animation section. */ public static class SectionBuilder { private String mId; private List mFrames = new ArrayList<>(); private boolean mIsOneshot = DEFAULT_ONESHOT_STATUS; private int mFrameDuration = DEFAULT_FRAME_DURATION; private Map mTransitions = new HashMap<>(); /** * A constructor that takes the ID of this section. * * @param id The ID of the section */ public SectionBuilder(String id) { mId = id; } /** * Add a frame to the section animation. * * @param imageResource The resource id of a image drawable. * @return This Builder object to allow for chaining of calls to set methods */ public SectionBuilder addFrame(int imageResource) { mFrames.add(imageResource); return this; } /** * Set that oneshot status of this section. * * @param isOneshot If true, the animation for this section will pause playing on the final frame. * If false, the animation for this section will loop until a new section is transitioned to. * @return This Builder object to allow for chaining of calls to set methods */ public SectionBuilder setOneshot(boolean isOneshot) { mIsOneshot = isOneshot; return this; } /** * Set the duration that each frame in this section will play. * * @param frameDuration The number of milliseconds that each frame will be displayed * @return This Builder object to allow for chaining of calls to set methods */ public SectionBuilder setFrameDuration(int frameDuration) { mFrameDuration = frameDuration; return this; } /** * Add an animation that will play when transitioning to this section. * * @param fromId A section name. When a transition is queued from the named section to this one, this transition will play. * @param transition The transition that will play. * @return This Builder object to allow for chaining of calls to set methods */ public SectionBuilder addTransition(String fromId, TransitionBuilder transition) { mTransitions.put(fromId, transition); return this; } private AnimationSection build(Context context) { AnimationDrawableLoader loader = new AnimationDrawableLoader(context, mFrameDuration, mIsOneshot, integerListToArray(mFrames)); AnimationSection section = new AnimationSection(mId, loader); for (Map.Entry entry : mTransitions.entrySet()) { loader = entry.getValue().build(context); section.addTransition(entry.getKey(), loader); } return section; } } /** * A builder for manually constructing a MultiStateAnimation. */ public static class Builder { List mSections = new ArrayList<>(); View mView = null; /** * Set a view to attach this animation to. * * The background of the view will contain the animation. * @param view The view that will hold the animation. */ public Builder(View view) { mView = view; } /** * Add an animation section. * @param section The section to add. * @return This Builder object to allow for chaining of calls to set methods */ public Builder addSection(SectionBuilder section) { mSections.add(section); return this; } /** * Construct a MultiStateAnimation. * @param context A context used to load resources. * @return A new MultiStateAnimation. */ public MultiStateAnimation build(Context context) { MultiStateAnimation animation = new MultiStateAnimation(mView); for (SectionBuilder section : mSections) { animation.addSection(section.build(context)); } return animation; } } /** * Creates a new MultiStateAnimation object from a json string. *

* The document must have the following structure: *

     *  {
     *      "first_section": {
     *          "oneshot": false,
     *          "frame_duration": 33,
     *          "frames": [
     *              "frame_01",
     *              "frame_02"
     *          ],
     *
     *      }
     *      "second_section": {
     *          "oneshot": true,
     *          "frames": [
     *              "other_frame_01"
     *          ],
     *          "transitions_from": {
     *              "first_section": {
     *                  "frame_duration": 33,
     *                  "frames": [
     *                          "first_to_second_transition_001",
     *                          "first_to_second_transition_002"
     *                  ]
     *              }
     *              "": {
     *                  "frames": [
     *                      "nothing_to_second_001",
     *                      "nothing_to_second_002"
     *                  ]
     *              }
     *          }
     *      }
     *  }
     * 
* The key for each entry is the ID of the state. *
*
"oneshot"
*
If false, the animation will play in a loop instead of stopping at the last * frame.
*
"frame_duration"
The number of milliseconds that each frame in the "frame" * list will play. It defaults to 33 (30fps) if not given.
*
"frames"
A list of string resource ID names that must correspond to a * drawable resource.
*
"transitions_from"
Optional, and is a set of animations that play when transitioning to * the current state from another given state. A transition will play when the ID of the * current state matches the transition's key and the state is transitioning to the state * in which the transition is defined.
*
* * @param context The application Context. * @param view If not null, animations will be set as the background of this view. * @param resid The resource ID the the raw json document. * @return A new MultiStateAnimation. * @throws RuntimeException */ public static MultiStateAnimation fromJsonResource(Context context, View view, int resid) { // Use the cached builder, if one exists. if (mBuilderCache.containsKey(resid)) { return mBuilderCache.get(resid).build(context); } // Read the resource into a string BufferedReader r = new BufferedReader(new InputStreamReader(context.getResources().openRawResource(resid))); StringBuilder stringBuilder = new StringBuilder(); String line; try { while ((line = r.readLine()) != null) { stringBuilder.append(line); } } catch (IOException ignored) { throw new RuntimeException("Cannot Read JSON sync animation Resource"); } // Parse Builder animationBuilder = new Builder(view); try { JSONObject root = new JSONObject(stringBuilder.toString()); // The root is a an object with keys that are sequence IDs for (Iterator iter = root.keys(); iter.hasNext(); ) { String sectionId = iter.next(); JSONObject obj = root.getJSONObject(sectionId); int frameDuration = obj.optInt("frame_duration", DEFAULT_FRAME_DURATION); boolean isOneShot = obj.optBoolean("oneshot", DEFAULT_ONESHOT_STATUS); JSONArray frames = obj.getJSONArray("frames"); SectionBuilder sectionBuilder = new SectionBuilder(sectionId) .setFrameDuration(frameDuration) .setOneshot(isOneShot); for (String frame : jsonArrayToArray(frames)) { sectionBuilder.addFrame(getDrawableResourceId(context, frame)); } JSONObject transitions_from; if (obj.has("transitions_from")) { transitions_from = obj.getJSONObject("transitions_from"); } else { transitions_from = new JSONObject(); } // The optional "transitions" entry is another list of objects for (Iterator transition_iter = transitions_from.keys(); transition_iter.hasNext(); ) { String from = transition_iter.next(); JSONObject t_obj = transitions_from.getJSONObject(from); frameDuration = t_obj.optInt("frame_duration", DEFAULT_FRAME_DURATION); frames = t_obj.getJSONArray("frames"); TransitionBuilder transitionBuilder = new TransitionBuilder() .setFrameDuration(frameDuration); for (String frame : jsonArrayToArray(frames)) { transitionBuilder.addFrame(getDrawableResourceId(context, frame)); } sectionBuilder.addTransition(from, transitionBuilder); } animationBuilder.addSection(sectionBuilder); } } catch (JSONException ignored) { throw new RuntimeException("Invalid sync animation JSON file format."); } mBuilderCache.put(resid, animationBuilder); return animationBuilder.build(context); } /** * Create a MultiStateAnimation from a JSON resource without a connected View. * * @param context the Application context. * @param resid The resource ID the the raw json document. * @return A new MultiStateAnimation instance. * @throws RuntimeException */ public static MultiStateAnimation fromJsonResource(Context context, int resid) { return MultiStateAnimation.fromJsonResource(context, null, resid); } /** * Add an animation section to this series. * * @param section the section to add. */ private void addSection(AnimationSection section) { mSectionsById.put(section.getId(), section); } /** * Returns the registered listener, if one exists. */ public AnimationSeriesListener getSeriesAnimationFinishedListener() { return mListener.get(); } /** * Registers a listener that will be called when a running animation finishes. If the * animation is continuous, the listener will be called every time the last frame of the * animation is played. * * @param listener The listener to register. */ public void setSeriesAnimationFinishedListener(AnimationSeriesListener listener) { this.mListener = new WeakReference(listener); } /** * Calculates the total duration of the current animation section, including the transition * if applicable. If the the animation is not a oneshot, the total will be for a single loop. * * @return The total animation duration, or 0 if no animation is playing. */ public int currentSectionDuration() { if (mCurrentSection == null) return 0; return mCurrentSection.getDuration(mTransitioningFromId); } /** * Returns the currently playing animation. If no animation has played since this object was * created or since a call to {@link #clearAnimation()}, null is returned. */ public AnimationDrawable getCurrentDrawable() { return mCurrentDrawable; } /** * Return the ID of the current section if one is playing, or null otherwise. */ public String getCurrentSectionId() { return mCurrentSection == null ? null : mCurrentSection.getId(); } /** * If the currently playing animation is a transition, return the ID of the * section that is being transitioned from. Otherwise return null. */ public String getTransitioningFromId() { return mTransitioningFromId; } /** * Play an animation drawable. * * @param drawable The drawable to play. */ @TargetApi(16) private void playDrawable(NotifyingAnimationDrawable drawable) { mCurrentDrawable = drawable; mCurrentDrawable.setAnimationFinishedListener(this); AnimationSeriesListener listener = mListener.get(); if (listener != null) { listener.onAnimationStarting(); } if (mView != null) { if (Build.VERSION.SDK_INT >= 16) { mView.setBackground(mCurrentDrawable); } else { mView.setBackgroundDrawable(mCurrentDrawable); } } mCurrentDrawable.start(); } /** * Queues a section to start as soon as the current animation finishes. * If no animation is playing, the queued animation will be started immediately. * Queueing a transition to the currently playing section has no effect. * * @param id The name of the section that will be queued. */ public void queueTransition(String id) { if (id.equals(getCurrentSectionId())) return; if (mCurrentSection == null || mCurrentDrawable != null && mCurrentDrawable.isOneShot() && mCurrentDrawable.isFinished()) { transitionNow(id); } else { mQueuedSectionId = id; } } /** * Starts a specific section without waiting for the current animation to finish. * If there is a defined transition from the current section to the new one, the * transition will be played, followed immediately by the regular section animation. * Transitioning to the currently playing section will restart the animation. * * @param id The name of the section that will be played. */ public void transitionNow(String id) { AnimationSection newSection = mSectionsById.get(id); if (newSection == null) { throw new IllegalArgumentException("transitionNow called with invalid id: " + id); } // If the section has a transition from the old section, play the // transition before the main animation. NotifyingAnimationDrawable transition = mCurrentSection == null ? newSection.getTransition("") : newSection.getTransition(mCurrentSection.getId()); if (transition != null) { mCurrentDrawable = transition; mTransitioningFromId = mCurrentSection == null ? "" : mCurrentSection.getId(); } else { mCurrentDrawable = newSection.loadDrawable(); mTransitioningFromId = null; } mCurrentSection = newSection; mQueuedSectionId = null; playDrawable(mCurrentDrawable); } /** * Clear any currently playing animation. This will cause a "" transition to * be played before the next queued section, if one was defined. */ public void clearAnimation() { if (mCurrentDrawable != null) { mCurrentDrawable.stop(); } if (mView != null) { mView.setBackgroundResource(0); } mCurrentDrawable = null; mCurrentSection = null; mQueuedSectionId = null; mTransitioningFromId = null; } /** * Callback that is run when a playing animation finishes. */ @Override public void onAnimationFinished() { AnimationSeriesListener listener = mListener.get(); if (listener != null) { listener.onAnimationFinished(); } if (mTransitioningFromId != null) { mTransitioningFromId = null; playDrawable(mCurrentSection.loadDrawable()); } else if (mQueuedSectionId != null) { transitionNow(mQueuedSectionId); } } } ================================================ FILE: library/src/main/java/com/getkeepsafe/android/multistateanimation/NotifyingAnimationDrawable.java ================================================ package com.getkeepsafe.android.multistateanimation; import android.graphics.drawable.AnimationDrawable; import java.lang.ref.WeakReference; /** * Extends AnimationDrawable to signal an event when the animation finishes. * This class behaves identically to a normal AnimationDrawable, but contains a method for * registering a callback that is called whenever the final frame of the animation is played. * If the animation is continuous, the callback will be called repeatedly while the animation * is running. * * @author AJ Alt */ public class NotifyingAnimationDrawable extends AnimationDrawable { public interface OnAnimationFinishedListener { void onAnimationFinished(); } private boolean mFinished = false; private WeakReference mListener = new WeakReference(null); /** * @param drawable The frames data from animation will be copied into this instance. The animation object will be unchanged. */ public NotifyingAnimationDrawable(AnimationDrawable drawable) { for (int i = 0; i < drawable.getNumberOfFrames(); i++) { addFrame(drawable.getFrame(i), drawable.getDuration(i)); } setOneShot(drawable.isOneShot()); } public NotifyingAnimationDrawable() { super(); } /** * @return The registered animation listener, or null if none exists. */ public OnAnimationFinishedListener getAnimationFinishedListener() { return mListener.get(); } /** * Sets a listener that will be called when the last frame of the animation is rendered. * If the animation is continuous, the listener will be called repeatedly while the animation * is running. * * @param listener The listener to register. */ public void setAnimationFinishedListener(OnAnimationFinishedListener listener) { this.mListener = new WeakReference(listener); } /** * Indicates whether the animation has ever finished. */ public boolean isFinished() { return mFinished; } @Override public boolean selectDrawable(int idx) { boolean result = super.selectDrawable(idx); if (idx != 0 && idx == getNumberOfFrames() - 1) { if (!mFinished || !isOneShot()) { mFinished = true; OnAnimationFinishedListener listener = mListener.get(); if (listener != null) { listener.onAnimationFinished(); } } } return result; } } ================================================ FILE: samples/.gitignore ================================================ /build /src/version/ ================================================ FILE: samples/AndroidManifest.xml ================================================ ================================================ FILE: samples/build.gradle ================================================ buildscript { repositories { mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:1.2.3' } } apply plugin: 'com.android.application' repositories { mavenCentral() } dependencies { compile project(':library') } android { compileSdkVersion 22 buildToolsVersion "22.0.1" defaultConfig { minSdkVersion 1 targetSdkVersion 22 applicationId "com.getkeepsafe.android.multistateanimation.samples" versionCode 3 versionName "1.1.1" } sourceSets { main { manifest.srcFile 'AndroidManifest.xml' res.srcDirs = ['res'] assets.srcDirs = ['assets'] } } lintOptions { abortOnError false } } ================================================ FILE: samples/res/layout/activity_three_state_sample.xml ================================================