├── .gitignore ├── .idea ├── .name ├── compiler.xml ├── copyright │ └── profiles_settings.xml ├── encodings.xml ├── gradle.xml ├── misc.xml ├── modules.xml ├── runConfigurations.xml └── vcs.xml ├── LICENSE ├── README.md ├── art └── demo.gif ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── sample ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── com │ │ └── loopeer │ │ └── springheader │ │ └── sample │ │ ├── MainActivity.java │ │ ├── PtrActivity.java │ │ ├── SpringHeaderActivity.java │ │ └── SrlActivity.java │ └── res │ ├── layout │ ├── activity_main.xml │ ├── activity_ptr.xml │ ├── activity_spring_header.xml │ ├── activity_srl.xml │ ├── many_text_view.xml │ └── scroll_view.xml │ ├── mipmap-hdpi │ └── ic_launcher.png │ ├── mipmap-mdpi │ └── ic_launcher.png │ ├── mipmap-xhdpi │ └── ic_launcher.png │ ├── mipmap-xxhdpi │ └── ic_launcher.png │ ├── mipmap-xxxhdpi │ └── ic_launcher.png │ └── values │ ├── colors.xml │ ├── strings.xml │ └── styles.xml ├── settings.gradle └── springheader ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src └── main ├── AndroidManifest.xml ├── java └── com │ └── loopeer │ └── springheader │ ├── DependentViewBehavior.java │ ├── FixedNestedScrollView.java │ ├── MaterialProgressDrawable.java │ ├── RefreshHeader.java │ ├── SimpleRefreshHeader.java │ ├── SpringHeaderBehavior.java │ ├── ViewOffsetBehavior.java │ └── ViewOffsetHelper.java └── res ├── layout └── refresh_header_simple.xml └── values ├── attrs.xml └── strings.xml /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/workspace.xml 5 | /.idea/libraries 6 | .DS_Store 7 | /build 8 | /captures 9 | 10 | # Built application files 11 | *.apk 12 | *.ap_ 13 | 14 | # Files for the Dalvik VM 15 | *.dex 16 | 17 | # Java class files 18 | *.class 19 | 20 | # Generated files 21 | bin/ 22 | gen/ 23 | out/ 24 | 25 | # Gradle files 26 | .gradle/ 27 | build/ 28 | 29 | # Local configuration file (sdk path, etc) 30 | local.properties 31 | 32 | # Proguard folder generated by Eclipse 33 | proguard/ 34 | 35 | # Log Files 36 | *.log 37 | 38 | # Android Studio Navigation editor temp files 39 | .navigation/ 40 | 41 | # Android Studio captures folder 42 | captures/ 43 | 44 | # Intellij 45 | *.iml -------------------------------------------------------------------------------- /.idea/.name: -------------------------------------------------------------------------------- 1 | SpringHeader -------------------------------------------------------------------------------- /.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 22 | -------------------------------------------------------------------------------- /.idea/copyright/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /.idea/encodings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 24 | 25 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 12 | 13 | 14 | 26 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 53 | 54 | 55 | 56 | 57 | 1.8 58 | 59 | 64 | 65 | 66 | 67 | 68 | 69 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /.idea/runConfigurations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 12 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | SpringHeader 2 | ======== 3 | 4 | An implementation of spring-like header (known as pull-to-refresh) that using `CoordinatorLayout`. 5 | 6 | ![demo](art/demo.gif) 7 | 8 | Usage 9 | -------- 10 | 11 | ### Simple Way 12 | 13 | Just put a `com.loopeer.springheader.SimpleRefreshHeader` in your `CoordinatorLayout`, 14 | and add the attribute `app:layout_behavior="@string/dependent_view_behavior"` in the scroll view to let it scroll along header. 15 | 16 | ```xml 17 | 24 | 25 | 30 | 31 | 36 | 37 | 38 | ``` 39 | 40 | #### Note: 41 | 42 | You can use `DependentViewBehavior` on other views as well, and you can use it multiple times or not use it at all. 43 | 44 | The reason why we don't use `CoordinatorLayout.Behavior`'s layout dependency function is that it won't meet all our needs. 45 | 46 | #### Simple Customization 47 | 48 | `SimpleRefreshHeader` has three attributes `textBelowThreshold`, `textAboveThreshold` and `textRefreshing`. 49 | You can also set color scheme via java code. 50 | 51 | `SimpleRefreshHeader` has a `DefaultBehavior`, the `SpringHeaderBehavior`. 52 | And `SpringHeaderBehavior` has three params `behavior_originalOffset`, `behavior_hoveringRange` and `behavior_maxRange`: 53 | * `behavior_originalOffset` is the original offset of header; 54 | * `behavior_hoveringRange` is the range from original offset to hovering offset; 55 | * `behavior_maxRange` is the range from original offset to max offset. 56 | `SimpleRefreshHeader` has a default behavior set, but if you set any of above attributes, 57 | you may also add attribute `app:layout_behavior="@string/spring_header_behavior"` to make it work. 58 | 59 | ### Extended Way 60 | 61 | `com.loopeer.springheader.RefreshHeader` is the base class for implementing your own style of refresh header. 62 | 63 | Also you can make use of any `View`s to make it work, 64 | just hook it up through the `SpringHeaderCallback` sets on `SpringHeaderBehavior`: 65 | 66 | ```java 67 | public interface SpringHeaderCallback { 68 | void onScroll(int offset, float fraction); 69 | 70 | void onStateChanged(int newState); 71 | } 72 | ``` 73 | 74 | `onScroll()` method is called whenever the header offset changed. 75 | * `fraction = (currentOffset - originalOffset) / hoveringRange`. 76 | `fraction` starts from 0, and when `currentOffset` equals `hoveringOffset`, `fraction` equals `1`. 77 | 78 | `onStateChanged()` method is called whenever the header state changed. 79 | There are four states `STATE_COLLAPSED`, `STATE_HOVERING`, `STATE_DRAGGING` and `STATE_SETTLING`. 80 | 81 | `RefreshHeader` implements `SpringHeaderCallback`. 82 | 83 | References 84 | ======== 85 | 86 | This project is mainly referencing `Android Support Library`, 87 | including `Design Support Library` and `v4 Support Library`. 88 | There are three class `ViewOffsetBehavior`, `ViewOffsetHelper` and `MaterialProgressDrawable` 89 | copied from the `Android Support Library`. 90 | 91 | License 92 | ======== 93 | 94 | [Apache License Version 2.0](LICENSE) 95 | -------------------------------------------------------------------------------- /art/demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/loopeer/SpringHeader/362cf100aa6b52e706ab2fe9dfc08e0a484051d0/art/demo.gif -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | repositories { 5 | jcenter() 6 | } 7 | dependencies { 8 | classpath 'com.android.tools.build:gradle:1.5.0' 9 | 10 | // NOTE: Do not place your application dependencies here; they belong 11 | // in the individual module build.gradle files 12 | } 13 | } 14 | 15 | allprojects { 16 | repositories { 17 | jcenter() 18 | } 19 | } 20 | 21 | task clean(type: Delete) { 22 | delete rootProject.buildDir 23 | } 24 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m 13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | # org.gradle.parallel=true -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/loopeer/SpringHeader/362cf100aa6b52e706ab2fe9dfc08e0a484051d0/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Dec 28 10:00:20 PST 2015 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.8-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # Attempt to set APP_HOME 46 | # Resolve links: $0 may be a link 47 | PRG="$0" 48 | # Need this for relative symlinks. 49 | while [ -h "$PRG" ] ; do 50 | ls=`ls -ld "$PRG"` 51 | link=`expr "$ls" : '.*-> \(.*\)$'` 52 | if expr "$link" : '/.*' > /dev/null; then 53 | PRG="$link" 54 | else 55 | PRG=`dirname "$PRG"`"/$link" 56 | fi 57 | done 58 | SAVED="`pwd`" 59 | cd "`dirname \"$PRG\"`/" >/dev/null 60 | APP_HOME="`pwd -P`" 61 | cd "$SAVED" >/dev/null 62 | 63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 64 | 65 | # Determine the Java command to use to start the JVM. 66 | if [ -n "$JAVA_HOME" ] ; then 67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 68 | # IBM's JDK on AIX uses strange locations for the executables 69 | JAVACMD="$JAVA_HOME/jre/sh/java" 70 | else 71 | JAVACMD="$JAVA_HOME/bin/java" 72 | fi 73 | if [ ! -x "$JAVACMD" ] ; then 74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 75 | 76 | Please set the JAVA_HOME variable in your environment to match the 77 | location of your Java installation." 78 | fi 79 | else 80 | JAVACMD="java" 81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 82 | 83 | Please set the JAVA_HOME variable in your environment to match the 84 | location of your Java installation." 85 | fi 86 | 87 | # Increase the maximum file descriptors if we can. 88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 89 | MAX_FD_LIMIT=`ulimit -H -n` 90 | if [ $? -eq 0 ] ; then 91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 92 | MAX_FD="$MAX_FD_LIMIT" 93 | fi 94 | ulimit -n $MAX_FD 95 | if [ $? -ne 0 ] ; then 96 | warn "Could not set maximum file descriptor limit: $MAX_FD" 97 | fi 98 | else 99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 100 | fi 101 | fi 102 | 103 | # For Darwin, add options to specify how the application appears in the dock 104 | if $darwin; then 105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 106 | fi 107 | 108 | # For Cygwin, switch paths to Windows format before running java 109 | if $cygwin ; then 110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 112 | JAVACMD=`cygpath --unix "$JAVACMD"` 113 | 114 | # We build the pattern for arguments to be converted via cygpath 115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 116 | SEP="" 117 | for dir in $ROOTDIRSRAW ; do 118 | ROOTDIRS="$ROOTDIRS$SEP$dir" 119 | SEP="|" 120 | done 121 | OURCYGPATTERN="(^($ROOTDIRS))" 122 | # Add a user-defined pattern to the cygpath arguments 123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 125 | fi 126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 127 | i=0 128 | for arg in "$@" ; do 129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 131 | 132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 134 | else 135 | eval `echo args$i`="\"$arg\"" 136 | fi 137 | i=$((i+1)) 138 | done 139 | case $i in 140 | (0) set -- ;; 141 | (1) set -- "$args0" ;; 142 | (2) set -- "$args0" "$args1" ;; 143 | (3) set -- "$args0" "$args1" "$args2" ;; 144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 150 | esac 151 | fi 152 | 153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 154 | function splitJvmOpts() { 155 | JVM_OPTS=("$@") 156 | } 157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 159 | 160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 161 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /sample/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /sample/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 23 5 | buildToolsVersion "23.0.2" 6 | 7 | defaultConfig { 8 | applicationId "com.loopeer.springheader.sample" 9 | minSdkVersion 11 10 | targetSdkVersion 23 11 | versionCode 1 12 | versionName "1.0" 13 | } 14 | buildTypes { 15 | release { 16 | minifyEnabled false 17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 18 | } 19 | } 20 | } 21 | 22 | dependencies { 23 | compile fileTree(dir: 'libs', include: ['*.jar']) 24 | 25 | compile project(':springheader') 26 | 27 | compile 'com.android.support:appcompat-v7:23.2.0' 28 | compile 'com.android.support:design:23.2.0' 29 | compile 'in.srain.cube:ultra-ptr:1.0.11' 30 | } 31 | -------------------------------------------------------------------------------- /sample/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in D:\Android\sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /sample/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 19 | 22 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /sample/src/main/java/com/loopeer/springheader/sample/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.loopeer.springheader.sample; 2 | 3 | import android.app.ListActivity; 4 | import android.content.Intent; 5 | import android.os.Bundle; 6 | import android.view.View; 7 | import android.widget.ArrayAdapter; 8 | import android.widget.ListView; 9 | 10 | public class MainActivity extends ListActivity { 11 | 12 | public static final String[] LABELS = new String[]{ 13 | "SpringHeader", 14 | "Ptr", 15 | "Srl" 16 | }; 17 | public static final Class[] CLASSES = new Class[]{ 18 | SpringHeaderActivity.class, 19 | PtrActivity.class, 20 | SrlActivity.class 21 | }; 22 | 23 | @Override 24 | protected void onCreate(Bundle savedInstanceState) { 25 | super.onCreate(savedInstanceState); 26 | 27 | setListAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, LABELS)); 28 | } 29 | 30 | @Override 31 | protected void onListItemClick(ListView l, View v, int position, long id) { 32 | super.onListItemClick(l, v, position, id); 33 | 34 | startActivity(new Intent(this, CLASSES[position])); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /sample/src/main/java/com/loopeer/springheader/sample/PtrActivity.java: -------------------------------------------------------------------------------- 1 | package com.loopeer.springheader.sample; 2 | 3 | import android.os.Bundle; 4 | import android.support.v4.widget.NestedScrollView; 5 | import android.support.v7.app.AppCompatActivity; 6 | import android.view.View; 7 | 8 | import in.srain.cube.views.ptr.PtrClassicFrameLayout; 9 | import in.srain.cube.views.ptr.PtrDefaultHandler; 10 | import in.srain.cube.views.ptr.PtrFrameLayout; 11 | import in.srain.cube.views.ptr.PtrHandler; 12 | 13 | public class PtrActivity extends AppCompatActivity { 14 | 15 | @Override 16 | protected void onCreate(Bundle savedInstanceState) { 17 | super.onCreate(savedInstanceState); 18 | setContentView(R.layout.activity_ptr); 19 | 20 | final NestedScrollView scrollView = (NestedScrollView) findViewById(R.id.scroll_view); 21 | final PtrClassicFrameLayout ptr = (PtrClassicFrameLayout) findViewById(R.id.ptr); 22 | ptr.setPtrHandler(new PtrHandler() { 23 | @Override 24 | public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) { 25 | return PtrDefaultHandler.checkContentCanBePulledDown(frame, scrollView, header); 26 | } 27 | 28 | @Override 29 | public void onRefreshBegin(PtrFrameLayout frame) { 30 | ptr.postDelayed(new Runnable() { 31 | @Override 32 | public void run() { 33 | ptr.refreshComplete(); 34 | } 35 | }, 2000); 36 | } 37 | }); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /sample/src/main/java/com/loopeer/springheader/sample/SpringHeaderActivity.java: -------------------------------------------------------------------------------- 1 | package com.loopeer.springheader.sample; 2 | 3 | import android.os.Bundle; 4 | import android.support.v7.app.AppCompatActivity; 5 | 6 | import com.loopeer.springheader.RefreshHeader; 7 | import com.loopeer.springheader.SimpleRefreshHeader; 8 | 9 | public class SpringHeaderActivity extends AppCompatActivity { 10 | 11 | @Override 12 | protected void onCreate(Bundle savedInstanceState) { 13 | super.onCreate(savedInstanceState); 14 | setContentView(R.layout.activity_spring_header); 15 | 16 | final SimpleRefreshHeader header = (SimpleRefreshHeader) findViewById(R.id.header); 17 | header.setOnRefreshListener(new RefreshHeader.OnRefreshListener() { 18 | @Override 19 | public void onRefresh() { 20 | header.postDelayed(new Runnable() { 21 | @Override 22 | public void run() { 23 | header.setRefreshing(false); 24 | } 25 | }, 2000); 26 | } 27 | }); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /sample/src/main/java/com/loopeer/springheader/sample/SrlActivity.java: -------------------------------------------------------------------------------- 1 | package com.loopeer.springheader.sample; 2 | 3 | import android.os.Bundle; 4 | import android.support.v4.widget.SwipeRefreshLayout; 5 | import android.support.v7.app.AppCompatActivity; 6 | 7 | public class SrlActivity extends AppCompatActivity { 8 | 9 | @Override 10 | protected void onCreate(Bundle savedInstanceState) { 11 | super.onCreate(savedInstanceState); 12 | setContentView(R.layout.activity_srl); 13 | 14 | final SwipeRefreshLayout srl = (SwipeRefreshLayout) findViewById(R.id.srl); 15 | srl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { 16 | @Override 17 | public void onRefresh() { 18 | srl.postDelayed(new Runnable() { 19 | @Override 20 | public void run() { 21 | srl.setRefreshing(false); 22 | } 23 | }, 2000); 24 | } 25 | }); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /sample/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | -------------------------------------------------------------------------------- /sample/src/main/res/layout/activity_ptr.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /sample/src/main/res/layout/activity_spring_header.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 15 | 16 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /sample/src/main/res/layout/activity_srl.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /sample/src/main/res/layout/many_text_view.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 9 | 10 | 15 | 16 | 21 | 22 | 27 | 28 | 33 | 34 | 39 | 40 | 45 | 46 | 51 | 52 | 57 | 58 | 63 | 64 | 69 | 70 | 75 | 76 | 81 | 82 | -------------------------------------------------------------------------------- /sample/src/main/res/layout/scroll_view.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 14 | 15 | 16 | 17 | 20 | 21 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 36 | 37 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/loopeer/SpringHeader/362cf100aa6b52e706ab2fe9dfc08e0a484051d0/sample/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/loopeer/SpringHeader/362cf100aa6b52e706ab2fe9dfc08e0a484051d0/sample/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/loopeer/SpringHeader/362cf100aa6b52e706ab2fe9dfc08e0a484051d0/sample/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/loopeer/SpringHeader/362cf100aa6b52e706ab2fe9dfc08e0a484051d0/sample/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/loopeer/SpringHeader/362cf100aa6b52e706ab2fe9dfc08e0a484051d0/sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #3F51B5 4 | #303F9F 5 | #FF4081 6 | 7 | -------------------------------------------------------------------------------- /sample/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | SpringHeader Sample 3 | 4 | -------------------------------------------------------------------------------- /sample/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':springheader', ':sample' 2 | -------------------------------------------------------------------------------- /springheader/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /springheader/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | 3 | android { 4 | compileSdkVersion 23 5 | buildToolsVersion "23.0.2" 6 | 7 | defaultConfig { 8 | minSdkVersion 11 9 | targetSdkVersion 23 10 | versionCode 1 11 | versionName "1.0" 12 | } 13 | buildTypes { 14 | release { 15 | minifyEnabled false 16 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 17 | } 18 | } 19 | } 20 | 21 | dependencies { 22 | compile fileTree(dir: 'libs', include: ['*.jar']) 23 | compile 'com.android.support:appcompat-v7:23.2.0' 24 | compile 'com.android.support:design:23.2.0' 25 | } 26 | -------------------------------------------------------------------------------- /springheader/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in D:\Android\sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /springheader/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /springheader/src/main/java/com/loopeer/springheader/DependentViewBehavior.java: -------------------------------------------------------------------------------- 1 | package com.loopeer.springheader; 2 | 3 | import android.content.Context; 4 | import android.support.design.widget.CoordinatorLayout; 5 | import android.util.AttributeSet; 6 | import android.view.View; 7 | 8 | public class DependentViewBehavior extends ViewOffsetBehavior { 9 | 10 | public DependentViewBehavior() { 11 | } 12 | 13 | public DependentViewBehavior(Context context, AttributeSet attrs) { 14 | super(context, attrs); 15 | } 16 | 17 | @Override 18 | public boolean layoutDependsOn(CoordinatorLayout parent, View child, View dependency) { 19 | CoordinatorLayout.Behavior behavior = getBehavior(dependency); 20 | return behavior instanceof SpringHeaderBehavior; 21 | } 22 | 23 | @Override 24 | public boolean onDependentViewChanged(CoordinatorLayout parent, View child, View dependency) { 25 | int offset = ((SpringHeaderBehavior) getBehavior(dependency)).getCurrentRange(); 26 | return setTopAndBottomOffset(offset); 27 | } 28 | 29 | private CoordinatorLayout.Behavior getBehavior(View view) { 30 | CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) view.getLayoutParams(); 31 | return lp.getBehavior(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /springheader/src/main/java/com/loopeer/springheader/FixedNestedScrollView.java: -------------------------------------------------------------------------------- 1 | package com.loopeer.springheader; 2 | 3 | import android.content.Context; 4 | import android.support.v4.widget.NestedScrollView; 5 | import android.util.AttributeSet; 6 | import android.view.View; 7 | 8 | public class FixedNestedScrollView extends NestedScrollView { 9 | public FixedNestedScrollView(Context context) { 10 | super(context); 11 | } 12 | 13 | public FixedNestedScrollView(Context context, AttributeSet attrs) { 14 | super(context, attrs); 15 | } 16 | 17 | public FixedNestedScrollView(Context context, AttributeSet attrs, int defStyleAttr) { 18 | super(context, attrs, defStyleAttr); 19 | } 20 | 21 | @Override 22 | public void onNestedPreScroll(View target, int dx, int dy, int[] consumed) { 23 | dispatchNestedPreScroll(0, dy, consumed, null); 24 | } 25 | 26 | // @Override 27 | // public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { 28 | // if (disallowIntercept) { 29 | // stopNestedScroll(); 30 | // } 31 | // super.requestDisallowInterceptTouchEvent(disallowIntercept); 32 | // } 33 | } 34 | -------------------------------------------------------------------------------- /springheader/src/main/java/com/loopeer/springheader/MaterialProgressDrawable.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.loopeer.springheader; 18 | 19 | import android.content.Context; 20 | import android.content.res.Resources; 21 | import android.graphics.Canvas; 22 | import android.graphics.Color; 23 | import android.graphics.ColorFilter; 24 | import android.graphics.Paint; 25 | import android.graphics.Paint.Style; 26 | import android.graphics.Path; 27 | import android.graphics.PixelFormat; 28 | import android.graphics.Rect; 29 | import android.graphics.RectF; 30 | import android.graphics.drawable.Animatable; 31 | import android.graphics.drawable.Drawable; 32 | import android.support.annotation.IntDef; 33 | import android.support.annotation.NonNull; 34 | import android.support.v4.view.animation.FastOutSlowInInterpolator; 35 | import android.util.DisplayMetrics; 36 | import android.view.View; 37 | import android.view.animation.Animation; 38 | import android.view.animation.Interpolator; 39 | import android.view.animation.LinearInterpolator; 40 | import android.view.animation.Transformation; 41 | 42 | import java.lang.annotation.Retention; 43 | import java.lang.annotation.RetentionPolicy; 44 | import java.util.ArrayList; 45 | 46 | /** 47 | * Fancy progress indicator for Material theme. 48 | * 49 | * @hide 50 | */ 51 | class MaterialProgressDrawable extends Drawable implements Animatable { 52 | private static final Interpolator LINEAR_INTERPOLATOR = new LinearInterpolator(); 53 | private static final Interpolator MATERIAL_INTERPOLATOR = new FastOutSlowInInterpolator(); 54 | 55 | private static final float FULL_ROTATION = 1080.0f; 56 | @Retention(RetentionPolicy.CLASS) 57 | @IntDef({LARGE, DEFAULT}) 58 | public @interface ProgressDrawableSize {} 59 | // Maps to ProgressBar.Large style 60 | static final int LARGE = 0; 61 | // Maps to ProgressBar default style 62 | static final int DEFAULT = 1; 63 | 64 | // Maps to ProgressBar default style 65 | private static final int CIRCLE_DIAMETER = 40; 66 | private static final float CENTER_RADIUS = 8.75f; //should add up to 10 when + stroke_width 67 | private static final float STROKE_WIDTH = 2.5f; 68 | 69 | // Maps to ProgressBar.Large style 70 | private static final int CIRCLE_DIAMETER_LARGE = 56; 71 | private static final float CENTER_RADIUS_LARGE = 12.5f; 72 | private static final float STROKE_WIDTH_LARGE = 3f; 73 | 74 | private final int[] COLORS = new int[] { 75 | Color.BLACK 76 | }; 77 | 78 | /** 79 | * The value in the linear interpolator for animating the drawable at which 80 | * the color transition should start 81 | */ 82 | private static final float COLOR_START_DELAY_OFFSET = 0.75f; 83 | private static final float END_TRIM_START_DELAY_OFFSET = 0.5f; 84 | private static final float START_TRIM_DURATION_OFFSET = 0.5f; 85 | 86 | /** The duration of a single progress spin in milliseconds. */ 87 | private static final int ANIMATION_DURATION = 1332; 88 | 89 | /** The number of points in the progress "star". */ 90 | private static final float NUM_POINTS = 5f; 91 | /** The list of animators operating on this drawable. */ 92 | private final ArrayList mAnimators = new ArrayList(); 93 | 94 | /** The indicator ring, used to manage animation state. */ 95 | private final Ring mRing; 96 | 97 | /** Canvas rotation in degrees. */ 98 | private float mRotation; 99 | 100 | /** Layout info for the arrowhead in dp */ 101 | private static final int ARROW_WIDTH = 10; 102 | private static final int ARROW_HEIGHT = 5; 103 | private static final float ARROW_OFFSET_ANGLE = 5; 104 | 105 | /** Layout info for the arrowhead for the large spinner in dp */ 106 | private static final int ARROW_WIDTH_LARGE = 12; 107 | private static final int ARROW_HEIGHT_LARGE = 6; 108 | private static final float MAX_PROGRESS_ARC = .8f; 109 | 110 | private Resources mResources; 111 | private View mParent; 112 | private Animation mAnimation; 113 | private float mRotationCount; 114 | private double mWidth; 115 | private double mHeight; 116 | boolean mFinishing; 117 | 118 | public MaterialProgressDrawable(Context context, View parent) { 119 | mParent = parent; 120 | mResources = context.getResources(); 121 | 122 | mRing = new Ring(mCallback); 123 | mRing.setColors(COLORS); 124 | 125 | updateSizes(DEFAULT); 126 | setupAnimators(); 127 | } 128 | 129 | private void setSizeParameters(double progressCircleWidth, double progressCircleHeight, 130 | double centerRadius, double strokeWidth, float arrowWidth, float arrowHeight) { 131 | final Ring ring = mRing; 132 | final DisplayMetrics metrics = mResources.getDisplayMetrics(); 133 | final float screenDensity = metrics.density; 134 | 135 | mWidth = progressCircleWidth * screenDensity; 136 | mHeight = progressCircleHeight * screenDensity; 137 | ring.setStrokeWidth((float) strokeWidth * screenDensity); 138 | ring.setCenterRadius(centerRadius * screenDensity); 139 | ring.setColorIndex(0); 140 | ring.setArrowDimensions(arrowWidth * screenDensity, arrowHeight * screenDensity); 141 | ring.setInsets((int) mWidth, (int) mHeight); 142 | } 143 | 144 | /** 145 | * Set the overall size for the progress spinner. This updates the radius 146 | * and stroke width of the ring. 147 | * 148 | * @param size One of {@link MaterialProgressDrawable.LARGE} or 149 | * {@link MaterialProgressDrawable.DEFAULT} 150 | */ 151 | public void updateSizes(@ProgressDrawableSize int size) { 152 | if (size == LARGE) { 153 | setSizeParameters(CIRCLE_DIAMETER_LARGE, CIRCLE_DIAMETER_LARGE, CENTER_RADIUS_LARGE, 154 | STROKE_WIDTH_LARGE, ARROW_WIDTH_LARGE, ARROW_HEIGHT_LARGE); 155 | } else { 156 | setSizeParameters(CIRCLE_DIAMETER, CIRCLE_DIAMETER, CENTER_RADIUS, STROKE_WIDTH, 157 | ARROW_WIDTH, ARROW_HEIGHT); 158 | } 159 | } 160 | 161 | /** 162 | * @param show Set to true to display the arrowhead on the progress spinner. 163 | */ 164 | public void showArrow(boolean show) { 165 | mRing.setShowArrow(show); 166 | } 167 | 168 | /** 169 | * @param scale Set the scale of the arrowhead for the spinner. 170 | */ 171 | public void setArrowScale(float scale) { 172 | mRing.setArrowScale(scale); 173 | } 174 | 175 | /** 176 | * Set the start and end trim for the progress spinner arc. 177 | * 178 | * @param startAngle start angle 179 | * @param endAngle end angle 180 | */ 181 | public void setStartEndTrim(float startAngle, float endAngle) { 182 | mRing.setStartTrim(startAngle); 183 | mRing.setEndTrim(endAngle); 184 | } 185 | 186 | /** 187 | * Set the amount of rotation to apply to the progress spinner. 188 | * 189 | * @param rotation Rotation is from [0..1] 190 | */ 191 | public void setProgressRotation(float rotation) { 192 | mRing.setRotation(rotation); 193 | } 194 | 195 | /** 196 | * Update the background color of the circle image view. 197 | */ 198 | public void setBackgroundColor(int color) { 199 | mRing.setBackgroundColor(color); 200 | } 201 | 202 | /** 203 | * Set the colors used in the progress animation from color resources. 204 | * The first color will also be the color of the bar that grows in response 205 | * to a user swipe gesture. 206 | * 207 | * @param colors 208 | */ 209 | public void setColorSchemeColors(int... colors) { 210 | mRing.setColors(colors); 211 | mRing.setColorIndex(0); 212 | } 213 | 214 | @Override 215 | public int getIntrinsicHeight() { 216 | return (int) mHeight; 217 | } 218 | 219 | @Override 220 | public int getIntrinsicWidth() { 221 | return (int) mWidth; 222 | } 223 | 224 | @Override 225 | public void draw(Canvas c) { 226 | final Rect bounds = getBounds(); 227 | final int saveCount = c.save(); 228 | c.rotate(mRotation, bounds.exactCenterX(), bounds.exactCenterY()); 229 | mRing.draw(c, bounds); 230 | c.restoreToCount(saveCount); 231 | } 232 | 233 | @Override 234 | public void setAlpha(int alpha) { 235 | mRing.setAlpha(alpha); 236 | } 237 | 238 | public int getAlpha() { 239 | return mRing.getAlpha(); 240 | } 241 | 242 | @Override 243 | public void setColorFilter(ColorFilter colorFilter) { 244 | mRing.setColorFilter(colorFilter); 245 | } 246 | 247 | @SuppressWarnings("unused") 248 | void setRotation(float rotation) { 249 | mRotation = rotation; 250 | invalidateSelf(); 251 | } 252 | 253 | @SuppressWarnings("unused") 254 | private float getRotation() { 255 | return mRotation; 256 | } 257 | 258 | @Override 259 | public int getOpacity() { 260 | return PixelFormat.TRANSLUCENT; 261 | } 262 | 263 | @Override 264 | public boolean isRunning() { 265 | final ArrayList animators = mAnimators; 266 | final int N = animators.size(); 267 | for (int i = 0; i < N; i++) { 268 | final Animation animator = animators.get(i); 269 | if (animator.hasStarted() && !animator.hasEnded()) { 270 | return true; 271 | } 272 | } 273 | return false; 274 | } 275 | 276 | @Override 277 | public void start() { 278 | mAnimation.reset(); 279 | mRing.storeOriginals(); 280 | // Already showing some part of the ring 281 | if (mRing.getEndTrim() != mRing.getStartTrim()) { 282 | mFinishing = true; 283 | mAnimation.setDuration(ANIMATION_DURATION/2); 284 | mParent.startAnimation(mAnimation); 285 | } else { 286 | mRing.setColorIndex(0); 287 | mRing.resetOriginals(); 288 | mAnimation.setDuration(ANIMATION_DURATION); 289 | mParent.startAnimation(mAnimation); 290 | } 291 | } 292 | 293 | @Override 294 | public void stop() { 295 | mParent.clearAnimation(); 296 | setRotation(0); 297 | mRing.setShowArrow(false); 298 | mRing.setColorIndex(0); 299 | mRing.resetOriginals(); 300 | } 301 | 302 | private float getMinProgressArc(Ring ring) { 303 | return (float) Math.toRadians( 304 | ring.getStrokeWidth() / (2 * Math.PI * ring.getCenterRadius())); 305 | } 306 | 307 | // Adapted from ArgbEvaluator.java 308 | private int evaluateColorChange(float fraction, int startValue, int endValue) { 309 | int startInt = (Integer) startValue; 310 | int startA = (startInt >> 24) & 0xff; 311 | int startR = (startInt >> 16) & 0xff; 312 | int startG = (startInt >> 8) & 0xff; 313 | int startB = startInt & 0xff; 314 | 315 | int endInt = (Integer) endValue; 316 | int endA = (endInt >> 24) & 0xff; 317 | int endR = (endInt >> 16) & 0xff; 318 | int endG = (endInt >> 8) & 0xff; 319 | int endB = endInt & 0xff; 320 | 321 | return (int)((startA + (int)(fraction * (endA - startA))) << 24) | 322 | (int)((startR + (int)(fraction * (endR - startR))) << 16) | 323 | (int)((startG + (int)(fraction * (endG - startG))) << 8) | 324 | (int)((startB + (int)(fraction * (endB - startB)))); 325 | } 326 | 327 | /** 328 | * Update the ring color if this is within the last 25% of the animation. 329 | * The new ring color will be a translation from the starting ring color to 330 | * the next color. 331 | */ 332 | private void updateRingColor(float interpolatedTime, Ring ring) { 333 | if (interpolatedTime > COLOR_START_DELAY_OFFSET) { 334 | // scale the interpolatedTime so that the full 335 | // transformation from 0 - 1 takes place in the 336 | // remaining time 337 | ring.setColor(evaluateColorChange((interpolatedTime - COLOR_START_DELAY_OFFSET) 338 | / (1.0f - COLOR_START_DELAY_OFFSET), ring.getStartingColor(), 339 | ring.getNextColor())); 340 | } 341 | } 342 | 343 | private void applyFinishTranslation(float interpolatedTime, Ring ring) { 344 | // shrink back down and complete a full rotation before 345 | // starting other circles 346 | // Rotation goes between [0..1]. 347 | updateRingColor(interpolatedTime, ring); 348 | float targetRotation = (float) (Math.floor(ring.getStartingRotation() / MAX_PROGRESS_ARC) 349 | + 1f); 350 | final float minProgressArc = getMinProgressArc(ring); 351 | final float startTrim = ring.getStartingStartTrim() 352 | + (ring.getStartingEndTrim() - minProgressArc - ring.getStartingStartTrim()) 353 | * interpolatedTime; 354 | ring.setStartTrim(startTrim); 355 | ring.setEndTrim(ring.getStartingEndTrim()); 356 | final float rotation = ring.getStartingRotation() 357 | + ((targetRotation - ring.getStartingRotation()) * interpolatedTime); 358 | ring.setRotation(rotation); 359 | } 360 | 361 | private void setupAnimators() { 362 | final Ring ring = mRing; 363 | final Animation animation = new Animation() { 364 | @Override 365 | public void applyTransformation(float interpolatedTime, Transformation t) { 366 | if (mFinishing) { 367 | applyFinishTranslation(interpolatedTime, ring); 368 | } else { 369 | // The minProgressArc is calculated from 0 to create an 370 | // angle that matches the stroke width. 371 | final float minProgressArc = getMinProgressArc(ring); 372 | final float startingEndTrim = ring.getStartingEndTrim(); 373 | final float startingTrim = ring.getStartingStartTrim(); 374 | final float startingRotation = ring.getStartingRotation(); 375 | 376 | updateRingColor(interpolatedTime, ring); 377 | 378 | // Moving the start trim only occurs in the first 50% of a 379 | // single ring animation 380 | if (interpolatedTime <= START_TRIM_DURATION_OFFSET) { 381 | // scale the interpolatedTime so that the full 382 | // transformation from 0 - 1 takes place in the 383 | // remaining time 384 | final float scaledTime = (interpolatedTime) 385 | / (1.0f - START_TRIM_DURATION_OFFSET); 386 | final float startTrim = startingTrim 387 | + ((MAX_PROGRESS_ARC - minProgressArc) * MATERIAL_INTERPOLATOR 388 | .getInterpolation(scaledTime)); 389 | ring.setStartTrim(startTrim); 390 | } 391 | 392 | // Moving the end trim starts after 50% of a single ring 393 | // animation completes 394 | if (interpolatedTime > END_TRIM_START_DELAY_OFFSET) { 395 | // scale the interpolatedTime so that the full 396 | // transformation from 0 - 1 takes place in the 397 | // remaining time 398 | final float minArc = MAX_PROGRESS_ARC - minProgressArc; 399 | float scaledTime = (interpolatedTime - START_TRIM_DURATION_OFFSET) 400 | / (1.0f - START_TRIM_DURATION_OFFSET); 401 | final float endTrim = startingEndTrim 402 | + (minArc * MATERIAL_INTERPOLATOR.getInterpolation(scaledTime)); 403 | ring.setEndTrim(endTrim); 404 | } 405 | 406 | final float rotation = startingRotation + (0.25f * interpolatedTime); 407 | ring.setRotation(rotation); 408 | 409 | float groupRotation = ((FULL_ROTATION / NUM_POINTS) * interpolatedTime) 410 | + (FULL_ROTATION * (mRotationCount / NUM_POINTS)); 411 | setRotation(groupRotation); 412 | } 413 | } 414 | }; 415 | animation.setRepeatCount(Animation.INFINITE); 416 | animation.setRepeatMode(Animation.RESTART); 417 | animation.setInterpolator(LINEAR_INTERPOLATOR); 418 | animation.setAnimationListener(new Animation.AnimationListener() { 419 | 420 | @Override 421 | public void onAnimationStart(Animation animation) { 422 | mRotationCount = 0; 423 | } 424 | 425 | @Override 426 | public void onAnimationEnd(Animation animation) { 427 | // do nothing 428 | } 429 | 430 | @Override 431 | public void onAnimationRepeat(Animation animation) { 432 | ring.storeOriginals(); 433 | ring.goToNextColor(); 434 | ring.setStartTrim(ring.getEndTrim()); 435 | if (mFinishing) { 436 | // finished closing the last ring from the swipe gesture; go 437 | // into progress mode 438 | mFinishing = false; 439 | animation.setDuration(ANIMATION_DURATION); 440 | ring.setShowArrow(false); 441 | } else { 442 | mRotationCount = (mRotationCount + 1) % (NUM_POINTS); 443 | } 444 | } 445 | }); 446 | mAnimation = animation; 447 | } 448 | 449 | private final Callback mCallback = new Callback() { 450 | @Override 451 | public void invalidateDrawable(Drawable d) { 452 | invalidateSelf(); 453 | } 454 | 455 | @Override 456 | public void scheduleDrawable(Drawable d, Runnable what, long when) { 457 | scheduleSelf(what, when); 458 | } 459 | 460 | @Override 461 | public void unscheduleDrawable(Drawable d, Runnable what) { 462 | unscheduleSelf(what); 463 | } 464 | }; 465 | 466 | private static class Ring { 467 | private final RectF mTempBounds = new RectF(); 468 | private final Paint mPaint = new Paint(); 469 | private final Paint mArrowPaint = new Paint(); 470 | 471 | private final Callback mCallback; 472 | 473 | private float mStartTrim = 0.0f; 474 | private float mEndTrim = 0.0f; 475 | private float mRotation = 0.0f; 476 | private float mStrokeWidth = 5.0f; 477 | private float mStrokeInset = 2.5f; 478 | 479 | private int[] mColors; 480 | // mColorIndex represents the offset into the available mColors that the 481 | // progress circle should currently display. As the progress circle is 482 | // animating, the mColorIndex moves by one to the next available color. 483 | private int mColorIndex; 484 | private float mStartingStartTrim; 485 | private float mStartingEndTrim; 486 | private float mStartingRotation; 487 | private boolean mShowArrow; 488 | private Path mArrow; 489 | private float mArrowScale; 490 | private double mRingCenterRadius; 491 | private int mArrowWidth; 492 | private int mArrowHeight; 493 | private int mAlpha; 494 | private final Paint mCirclePaint = new Paint(Paint.ANTI_ALIAS_FLAG); 495 | private int mBackgroundColor; 496 | private int mCurrentColor; 497 | 498 | public Ring(Callback callback) { 499 | mCallback = callback; 500 | 501 | mPaint.setStrokeCap(Paint.Cap.SQUARE); 502 | mPaint.setAntiAlias(true); 503 | mPaint.setStyle(Style.STROKE); 504 | 505 | mArrowPaint.setStyle(Style.FILL); 506 | mArrowPaint.setAntiAlias(true); 507 | } 508 | 509 | public void setBackgroundColor(int color) { 510 | mBackgroundColor = color; 511 | } 512 | 513 | /** 514 | * Set the dimensions of the arrowhead. 515 | * 516 | * @param width Width of the hypotenuse of the arrow head 517 | * @param height Height of the arrow point 518 | */ 519 | public void setArrowDimensions(float width, float height) { 520 | mArrowWidth = (int) width; 521 | mArrowHeight = (int) height; 522 | } 523 | 524 | /** 525 | * Draw the progress spinner 526 | */ 527 | public void draw(Canvas c, Rect bounds) { 528 | final RectF arcBounds = mTempBounds; 529 | arcBounds.set(bounds); 530 | arcBounds.inset(mStrokeInset, mStrokeInset); 531 | 532 | final float startAngle = (mStartTrim + mRotation) * 360; 533 | final float endAngle = (mEndTrim + mRotation) * 360; 534 | float sweepAngle = endAngle - startAngle; 535 | 536 | mPaint.setColor(mCurrentColor); 537 | c.drawArc(arcBounds, startAngle, sweepAngle, false, mPaint); 538 | 539 | drawTriangle(c, startAngle, sweepAngle, bounds); 540 | 541 | if (mAlpha < 255) { 542 | mCirclePaint.setColor(mBackgroundColor); 543 | mCirclePaint.setAlpha(255 - mAlpha); 544 | c.drawCircle(bounds.exactCenterX(), bounds.exactCenterY(), bounds.width() / 2, 545 | mCirclePaint); 546 | } 547 | } 548 | 549 | private void drawTriangle(Canvas c, float startAngle, float sweepAngle, Rect bounds) { 550 | if (mShowArrow) { 551 | if (mArrow == null) { 552 | mArrow = new Path(); 553 | mArrow.setFillType(Path.FillType.EVEN_ODD); 554 | } else { 555 | mArrow.reset(); 556 | } 557 | 558 | // Adjust the position of the triangle so that it is inset as 559 | // much as the arc, but also centered on the arc. 560 | float inset = (int) mStrokeInset / 2 * mArrowScale; 561 | float x = (float) (mRingCenterRadius * Math.cos(0) + bounds.exactCenterX()); 562 | float y = (float) (mRingCenterRadius * Math.sin(0) + bounds.exactCenterY()); 563 | 564 | // Update the path each time. This works around an issue in SKIA 565 | // where concatenating a rotation matrix to a scale matrix 566 | // ignored a starting negative rotation. This appears to have 567 | // been fixed as of API 21. 568 | mArrow.moveTo(0, 0); 569 | mArrow.lineTo(mArrowWidth * mArrowScale, 0); 570 | mArrow.lineTo((mArrowWidth * mArrowScale / 2), (mArrowHeight 571 | * mArrowScale)); 572 | mArrow.offset(x - inset, y); 573 | mArrow.close(); 574 | // draw a triangle 575 | mArrowPaint.setColor(mCurrentColor); 576 | c.rotate(startAngle + sweepAngle - ARROW_OFFSET_ANGLE, bounds.exactCenterX(), 577 | bounds.exactCenterY()); 578 | c.drawPath(mArrow, mArrowPaint); 579 | } 580 | } 581 | 582 | /** 583 | * Set the colors the progress spinner alternates between. 584 | * 585 | * @param colors Array of integers describing the colors. Must be non-null. 586 | */ 587 | public void setColors(@NonNull int[] colors) { 588 | mColors = colors; 589 | // if colors are reset, make sure to reset the color index as well 590 | setColorIndex(0); 591 | } 592 | 593 | /** 594 | * Set the absolute color of the progress spinner. This is should only 595 | * be used when animating between current and next color when the 596 | * spinner is rotating. 597 | * 598 | * @param color int describing the color. 599 | */ 600 | public void setColor(int color) { 601 | mCurrentColor = color; 602 | } 603 | 604 | /** 605 | * @param index Index into the color array of the color to display in 606 | * the progress spinner. 607 | */ 608 | public void setColorIndex(int index) { 609 | mColorIndex = index; 610 | mCurrentColor = mColors[mColorIndex]; 611 | } 612 | 613 | /** 614 | * @return int describing the next color the progress spinner should use when drawing. 615 | */ 616 | public int getNextColor() { 617 | return mColors[getNextColorIndex()]; 618 | } 619 | 620 | private int getNextColorIndex() { 621 | return (mColorIndex + 1) % (mColors.length); 622 | } 623 | 624 | /** 625 | * Proceed to the next available ring color. This will automatically 626 | * wrap back to the beginning of colors. 627 | */ 628 | public void goToNextColor() { 629 | setColorIndex(getNextColorIndex()); 630 | } 631 | 632 | public void setColorFilter(ColorFilter filter) { 633 | mPaint.setColorFilter(filter); 634 | invalidateSelf(); 635 | } 636 | 637 | /** 638 | * @param alpha Set the alpha of the progress spinner and associated arrowhead. 639 | */ 640 | public void setAlpha(int alpha) { 641 | mAlpha = alpha; 642 | } 643 | 644 | /** 645 | * @return Current alpha of the progress spinner and arrowhead. 646 | */ 647 | public int getAlpha() { 648 | return mAlpha; 649 | } 650 | 651 | /** 652 | * @param strokeWidth Set the stroke width of the progress spinner in pixels. 653 | */ 654 | public void setStrokeWidth(float strokeWidth) { 655 | mStrokeWidth = strokeWidth; 656 | mPaint.setStrokeWidth(strokeWidth); 657 | invalidateSelf(); 658 | } 659 | 660 | @SuppressWarnings("unused") 661 | public float getStrokeWidth() { 662 | return mStrokeWidth; 663 | } 664 | 665 | @SuppressWarnings("unused") 666 | public void setStartTrim(float startTrim) { 667 | mStartTrim = startTrim; 668 | invalidateSelf(); 669 | } 670 | 671 | @SuppressWarnings("unused") 672 | public float getStartTrim() { 673 | return mStartTrim; 674 | } 675 | 676 | public float getStartingStartTrim() { 677 | return mStartingStartTrim; 678 | } 679 | 680 | public float getStartingEndTrim() { 681 | return mStartingEndTrim; 682 | } 683 | 684 | public int getStartingColor() { 685 | return mColors[mColorIndex]; 686 | } 687 | 688 | @SuppressWarnings("unused") 689 | public void setEndTrim(float endTrim) { 690 | mEndTrim = endTrim; 691 | invalidateSelf(); 692 | } 693 | 694 | @SuppressWarnings("unused") 695 | public float getEndTrim() { 696 | return mEndTrim; 697 | } 698 | 699 | @SuppressWarnings("unused") 700 | public void setRotation(float rotation) { 701 | mRotation = rotation; 702 | invalidateSelf(); 703 | } 704 | 705 | @SuppressWarnings("unused") 706 | public float getRotation() { 707 | return mRotation; 708 | } 709 | 710 | public void setInsets(int width, int height) { 711 | final float minEdge = (float) Math.min(width, height); 712 | float insets; 713 | if (mRingCenterRadius <= 0 || minEdge < 0) { 714 | insets = (float) Math.ceil(mStrokeWidth / 2.0f); 715 | } else { 716 | insets = (float) (minEdge / 2.0f - mRingCenterRadius); 717 | } 718 | mStrokeInset = insets; 719 | } 720 | 721 | @SuppressWarnings("unused") 722 | public float getInsets() { 723 | return mStrokeInset; 724 | } 725 | 726 | /** 727 | * @param centerRadius Inner radius in px of the circle the progress 728 | * spinner arc traces. 729 | */ 730 | public void setCenterRadius(double centerRadius) { 731 | mRingCenterRadius = centerRadius; 732 | } 733 | 734 | public double getCenterRadius() { 735 | return mRingCenterRadius; 736 | } 737 | 738 | /** 739 | * @param show Set to true to show the arrow head on the progress spinner. 740 | */ 741 | public void setShowArrow(boolean show) { 742 | if (mShowArrow != show) { 743 | mShowArrow = show; 744 | invalidateSelf(); 745 | } 746 | } 747 | 748 | /** 749 | * @param scale Set the scale of the arrowhead for the spinner. 750 | */ 751 | public void setArrowScale(float scale) { 752 | if (scale != mArrowScale) { 753 | mArrowScale = scale; 754 | invalidateSelf(); 755 | } 756 | } 757 | 758 | /** 759 | * @return The amount the progress spinner is currently rotated, between [0..1]. 760 | */ 761 | public float getStartingRotation() { 762 | return mStartingRotation; 763 | } 764 | 765 | /** 766 | * If the start / end trim are offset to begin with, store them so that 767 | * animation starts from that offset. 768 | */ 769 | public void storeOriginals() { 770 | mStartingStartTrim = mStartTrim; 771 | mStartingEndTrim = mEndTrim; 772 | mStartingRotation = mRotation; 773 | } 774 | 775 | /** 776 | * Reset the progress spinner to default rotation, start and end angles. 777 | */ 778 | public void resetOriginals() { 779 | mStartingStartTrim = 0; 780 | mStartingEndTrim = 0; 781 | mStartingRotation = 0; 782 | setStartTrim(0); 783 | setEndTrim(0); 784 | setRotation(0); 785 | } 786 | 787 | private void invalidateSelf() { 788 | mCallback.invalidateDrawable(null); 789 | } 790 | } 791 | } 792 | -------------------------------------------------------------------------------- /springheader/src/main/java/com/loopeer/springheader/RefreshHeader.java: -------------------------------------------------------------------------------- 1 | package com.loopeer.springheader; 2 | 3 | import android.content.Context; 4 | import android.support.design.widget.CoordinatorLayout; 5 | import android.util.AttributeSet; 6 | import android.view.ViewGroup; 7 | import android.widget.FrameLayout; 8 | 9 | @CoordinatorLayout.DefaultBehavior(SpringHeaderBehavior.class) 10 | public class RefreshHeader extends FrameLayout implements SpringHeaderBehavior.SpringHeaderCallback { 11 | 12 | private SpringHeaderBehavior mBehavior; 13 | 14 | private OnRefreshListener mOnRefreshListener; 15 | 16 | public RefreshHeader(Context context) { 17 | this(context, null); 18 | } 19 | 20 | public RefreshHeader(Context context, AttributeSet attrs) { 21 | this(context, attrs, 0); 22 | } 23 | 24 | public RefreshHeader(Context context, AttributeSet attrs, int defStyleAttr) { 25 | super(context, attrs, defStyleAttr); 26 | } 27 | 28 | @Override 29 | protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 30 | super.onLayout(changed, left, top, right, bottom); 31 | ViewGroup.LayoutParams lp = getLayoutParams(); 32 | if (lp instanceof CoordinatorLayout.LayoutParams) { 33 | CoordinatorLayout.Behavior behavior = ((CoordinatorLayout.LayoutParams) lp).getBehavior(); 34 | if (behavior instanceof SpringHeaderBehavior) { 35 | mBehavior = (SpringHeaderBehavior) behavior; 36 | mBehavior.setSpringHeaderCallback(this); 37 | } 38 | } 39 | } 40 | 41 | @Override 42 | public void onScroll(int offset, float fraction) { 43 | } 44 | 45 | @Override 46 | public void onStateChanged(int newState) { 47 | if (newState == SpringHeaderBehavior.STATE_HOVERING) { 48 | if (mOnRefreshListener != null) { 49 | mOnRefreshListener.onRefresh(); 50 | } 51 | } 52 | } 53 | 54 | public void setRefreshing(boolean refreshing) { 55 | if (mBehavior != null) { 56 | mBehavior.setState(refreshing ? SpringHeaderBehavior.STATE_HOVERING 57 | : SpringHeaderBehavior.STATE_COLLAPSED); 58 | } 59 | } 60 | 61 | public void setOnRefreshListener(OnRefreshListener listener) { 62 | mOnRefreshListener = listener; 63 | } 64 | 65 | public interface OnRefreshListener { 66 | void onRefresh(); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /springheader/src/main/java/com/loopeer/springheader/SimpleRefreshHeader.java: -------------------------------------------------------------------------------- 1 | package com.loopeer.springheader; 2 | 3 | import android.content.Context; 4 | import android.content.res.TypedArray; 5 | import android.support.annotation.ColorInt; 6 | import android.support.annotation.ColorRes; 7 | import android.support.annotation.StringRes; 8 | import android.support.v4.content.ContextCompat; 9 | import android.util.AttributeSet; 10 | import android.widget.ImageView; 11 | import android.widget.TextView; 12 | 13 | public class SimpleRefreshHeader extends RefreshHeader { 14 | 15 | private TextView mText; 16 | private MaterialProgressDrawable mProgress; 17 | 18 | private CharSequence mTextBelowThreshold; 19 | private CharSequence mTextAboveThreshold; 20 | private CharSequence mTextRefreshing; 21 | 22 | private int mOldState; 23 | 24 | private boolean mBelowThreshold; 25 | 26 | public SimpleRefreshHeader(Context context) { 27 | this(context, null); 28 | } 29 | 30 | public SimpleRefreshHeader(Context context, AttributeSet attrs) { 31 | this(context, attrs, 0); 32 | } 33 | 34 | public SimpleRefreshHeader(Context context, AttributeSet attrs, int defStyleAttr) { 35 | super(context, attrs, defStyleAttr); 36 | 37 | inflate(context, R.layout.refresh_header_simple, this); 38 | 39 | ImageView icon = (ImageView) findViewById(android.R.id.icon); 40 | mText = (TextView) findViewById(android.R.id.text1); 41 | 42 | mProgress = new MaterialProgressDrawable(getContext(), this); 43 | mProgress.setAlpha(255); 44 | icon.setImageDrawable(mProgress); 45 | 46 | TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SimpleRefreshHeader, defStyleAttr, 0); 47 | CharSequence text = a.getText(R.styleable.SimpleRefreshHeader_textBelowThreshold); 48 | if (text != null) { 49 | setTextBelowThreshold(text); 50 | } else { 51 | setTextBelowThreshold(R.string.simple_refresh_header_text_below_threshold); 52 | } 53 | text = a.getText(R.styleable.SimpleRefreshHeader_textAboveThreshold); 54 | if (text != null) { 55 | setTextAboveThreshold(text); 56 | } else { 57 | setTextAboveThreshold(R.string.simple_refresh_header_text_above_threshold); 58 | } 59 | text = a.getText(R.styleable.SimpleRefreshHeader_textRefreshing); 60 | if (text != null) { 61 | setTextRefreshing(text); 62 | } else { 63 | setTextRefreshing(R.string.simple_refresh_header_text_refreshing); 64 | } 65 | a.recycle(); 66 | } 67 | 68 | public void setColorSchemeResources(@ColorRes int... colorResIds) { 69 | int[] colorRes = new int[colorResIds.length]; 70 | for (int i = 0; i < colorResIds.length; i++) { 71 | colorRes[i] = ContextCompat.getColor(getContext(), colorResIds[i]); 72 | } 73 | setColorSchemeColors(colorRes); 74 | } 75 | 76 | public void setColorSchemeColors(@ColorInt int... colors) { 77 | mProgress.setColorSchemeColors(colors); 78 | } 79 | 80 | public void setTextBelowThreshold(CharSequence textBelowThreshold) { 81 | mTextBelowThreshold = textBelowThreshold; 82 | } 83 | 84 | public void setTextBelowThreshold(@StringRes int textBelowThreshold) { 85 | mTextBelowThreshold = getResources().getText(textBelowThreshold); 86 | } 87 | 88 | public void setTextAboveThreshold(CharSequence textAboveThreshold) { 89 | mTextAboveThreshold = textAboveThreshold; 90 | } 91 | 92 | public void setTextAboveThreshold(@StringRes int textAboveThreshold) { 93 | mTextAboveThreshold = getResources().getText(textAboveThreshold); 94 | } 95 | 96 | public void setTextRefreshing(CharSequence textRefreshing) { 97 | mTextRefreshing = textRefreshing; 98 | } 99 | 100 | public void setTextRefreshing(@StringRes int textRefreshing) { 101 | mTextRefreshing = getResources().getText(textRefreshing); 102 | } 103 | 104 | @Override 105 | public void onScroll(int offset, float fraction) { 106 | super.onScroll(offset, fraction); 107 | 108 | boolean belowThreshold = fraction < 1; 109 | if (belowThreshold != mBelowThreshold) { 110 | mBelowThreshold = belowThreshold; 111 | mText.setText(belowThreshold ? mTextBelowThreshold : mTextAboveThreshold); 112 | } 113 | 114 | mProgress.showArrow(true); 115 | float clampedFraction = Math.min(1, fraction); 116 | mProgress.setStartEndTrim(0, 0.8f * clampedFraction); 117 | mProgress.setArrowScale(clampedFraction); 118 | mProgress.setProgressRotation(fraction + 0.1f); 119 | } 120 | 121 | @Override 122 | public void onStateChanged(int newState) { 123 | super.onStateChanged(newState); 124 | if (newState == SpringHeaderBehavior.STATE_HOVERING) { 125 | mText.setText(mTextRefreshing); 126 | mProgress.start(); 127 | } else if (mOldState == SpringHeaderBehavior.STATE_HOVERING) { 128 | mProgress.stop(); 129 | } 130 | mOldState = newState; 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /springheader/src/main/java/com/loopeer/springheader/SpringHeaderBehavior.java: -------------------------------------------------------------------------------- 1 | package com.loopeer.springheader; 2 | 3 | import android.animation.Animator; 4 | import android.animation.AnimatorListenerAdapter; 5 | import android.animation.ValueAnimator; 6 | import android.content.Context; 7 | import android.content.res.TypedArray; 8 | import android.support.design.widget.CoordinatorLayout; 9 | import android.support.v4.view.ViewCompat; 10 | import android.util.AttributeSet; 11 | import android.view.View; 12 | import android.view.animation.DecelerateInterpolator; 13 | 14 | public class SpringHeaderBehavior extends ViewOffsetBehavior { 15 | 16 | private static final int UNSET = Integer.MIN_VALUE; 17 | 18 | public static final int STATE_COLLAPSED = 1; 19 | public static final int STATE_HOVERING = 2; 20 | public static final int STATE_DRAGGING = 3; 21 | public static final int STATE_SETTLING = 4; 22 | 23 | private int mState = STATE_COLLAPSED; 24 | 25 | private SpringHeaderCallback mCallback; 26 | 27 | private float mTotalUnconsumed; 28 | 29 | private int mOriginalOffset = UNSET; 30 | private int mHoveringRange = UNSET; 31 | private int mMaxRange = UNSET; 32 | private int mHoveringOffset; 33 | 34 | private boolean mOriginalOffsetSet; 35 | 36 | private ValueAnimator mAnimator; 37 | private EndListener mEndListener; 38 | 39 | public SpringHeaderBehavior() { 40 | } 41 | 42 | public SpringHeaderBehavior(Context context, AttributeSet attrs) { 43 | super(context, attrs); 44 | 45 | TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SpringHeaderBehavior_Params); 46 | setOriginalOffset(a.getDimensionPixelSize( 47 | R.styleable.SpringHeaderBehavior_Params_behavior_originalOffset, UNSET)); 48 | setHoveringRange(a.getDimensionPixelSize( 49 | R.styleable.SpringHeaderBehavior_Params_behavior_hoveringRange, UNSET)); 50 | setMaxRange(a.getDimensionPixelSize( 51 | R.styleable.SpringHeaderBehavior_Params_behavior_maxRange, UNSET)); 52 | a.recycle(); 53 | } 54 | 55 | public void setOriginalOffset(int originalOffset) { 56 | mOriginalOffset = originalOffset; 57 | } 58 | 59 | public void setHoveringRange(int hoveringRange) { 60 | mHoveringRange = hoveringRange; 61 | mHoveringOffset = mOriginalOffset + mHoveringRange; 62 | } 63 | 64 | public void setMaxRange(int maxRange) { 65 | mMaxRange = maxRange; 66 | } 67 | 68 | @Override 69 | public boolean onLayoutChild(CoordinatorLayout parent, View child, int layoutDirection) { 70 | boolean handled = super.onLayoutChild(parent, child, layoutDirection); 71 | 72 | int parentHeight = parent.getHeight(); 73 | int childHeight = child.getHeight(); 74 | 75 | if (mOriginalOffset == UNSET) { 76 | setOriginalOffset(-childHeight); 77 | } 78 | if (mHoveringRange == UNSET) { 79 | setHoveringRange(childHeight); 80 | } 81 | if (mMaxRange == UNSET) { 82 | setMaxRange(parentHeight); 83 | } 84 | 85 | if (!mOriginalOffsetSet) { 86 | super.setTopAndBottomOffset(mOriginalOffset); 87 | mOriginalOffsetSet = true; 88 | } 89 | 90 | return handled; 91 | } 92 | 93 | @Override 94 | public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout, View child, 95 | View directTargetChild, View target, int nestedScrollAxes) { 96 | boolean started = (nestedScrollAxes & ViewCompat.SCROLL_AXIS_VERTICAL) != 0 97 | && mState != STATE_HOVERING; 98 | if (started && mAnimator != null && mAnimator.isRunning()) { 99 | mAnimator.cancel(); 100 | } 101 | return started; 102 | } 103 | 104 | @Override 105 | public void onNestedScrollAccepted(CoordinatorLayout coordinatorLayout, View child, 106 | View directTargetChild, View target, int nestedScrollAxes) { 107 | mTotalUnconsumed = calculateScrollUnconsumed(); 108 | } 109 | 110 | @Override 111 | public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, View child, View target, 112 | int dx, int dy, int[] consumed) { 113 | if (dy > 0 && mTotalUnconsumed > 0) { 114 | if (dy > mTotalUnconsumed) { 115 | consumed[1] = dy - (int) mTotalUnconsumed; 116 | mTotalUnconsumed = 0; 117 | } else { 118 | mTotalUnconsumed -= dy; 119 | consumed[1] = dy; 120 | } 121 | setTopAndBottomOffset(calculateScrollOffset()); 122 | setStateInternal(STATE_DRAGGING); 123 | } 124 | } 125 | 126 | @Override 127 | public void onNestedScroll(CoordinatorLayout coordinatorLayout, View child, View target, 128 | int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) { 129 | if (dyUnconsumed < 0) { 130 | mTotalUnconsumed -= dyUnconsumed; 131 | setTopAndBottomOffset(calculateScrollOffset()); 132 | setStateInternal(STATE_DRAGGING); 133 | } 134 | } 135 | 136 | @Override 137 | public void onStopNestedScroll(CoordinatorLayout coordinatorLayout, View child, View target) { 138 | animateOffsetToState(getTopAndBottomOffset() >= mHoveringOffset 139 | ? STATE_HOVERING : STATE_COLLAPSED); 140 | } 141 | 142 | private void animateOffsetToState(int endState) { 143 | int from = getTopAndBottomOffset(); 144 | int to = endState == STATE_HOVERING ? mHoveringOffset : mOriginalOffset; 145 | if (from == to) { 146 | setStateInternal(endState); 147 | return; 148 | } else { 149 | setStateInternal(STATE_SETTLING); 150 | } 151 | 152 | if (mAnimator == null) { 153 | mAnimator = new ValueAnimator(); 154 | mAnimator.setDuration(200); 155 | mAnimator.setInterpolator(new DecelerateInterpolator()); 156 | mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { 157 | @Override 158 | public void onAnimationUpdate(ValueAnimator animation) { 159 | setTopAndBottomOffset((int) animation.getAnimatedValue()); 160 | } 161 | }); 162 | mEndListener = new EndListener(endState); 163 | mAnimator.addListener(mEndListener); 164 | } else { 165 | if (mAnimator.isRunning()) { 166 | mAnimator.cancel(); 167 | } 168 | mEndListener.setEndState(endState); 169 | } 170 | mAnimator.setIntValues(from, to); 171 | mAnimator.start(); 172 | } 173 | 174 | @Override 175 | public boolean setTopAndBottomOffset(int offset) { 176 | if (mCallback != null) { 177 | mCallback.onScroll(offset, (float) (offset - mOriginalOffset) / mHoveringRange); 178 | } 179 | return super.setTopAndBottomOffset(offset); 180 | } 181 | 182 | private void setStateInternal(int state) { 183 | if (state == mState) { 184 | return; 185 | } 186 | mState = state; 187 | if (mCallback != null) { 188 | mCallback.onStateChanged(state); 189 | } 190 | } 191 | 192 | public void setState(int state) { 193 | if (state != STATE_COLLAPSED && state != STATE_HOVERING) { 194 | throw new IllegalArgumentException("Illegal state argument: " + state); 195 | } else if (state != mState) { 196 | animateOffsetToState(state); 197 | } 198 | } 199 | 200 | private int calculateScrollOffset() { 201 | return (int) (mMaxRange * (1 - Math.exp(-(mTotalUnconsumed / mMaxRange / 2)))) 202 | + mOriginalOffset; 203 | } 204 | 205 | private int calculateScrollUnconsumed() { 206 | return (int) (-Math.log(1 - (float) getCurrentRange() / mMaxRange) * mMaxRange * 2); 207 | } 208 | 209 | public int getCurrentRange() { 210 | return getTopAndBottomOffset() - mOriginalOffset; 211 | } 212 | 213 | public void setSpringHeaderCallback(SpringHeaderCallback callback) { 214 | mCallback = callback; 215 | } 216 | 217 | public interface SpringHeaderCallback { 218 | void onScroll(int offset, float fraction); 219 | 220 | void onStateChanged(int newState); 221 | } 222 | 223 | private class EndListener extends AnimatorListenerAdapter { 224 | 225 | private int mEndState; 226 | private boolean mCanceling; 227 | 228 | public EndListener(int endState) { 229 | mEndState = endState; 230 | } 231 | 232 | public void setEndState(int finalState) { 233 | mEndState = finalState; 234 | } 235 | 236 | @Override 237 | public void onAnimationStart(Animator animation) { 238 | mCanceling = false; 239 | } 240 | 241 | @Override 242 | public void onAnimationCancel(Animator animation) { 243 | mCanceling = true; 244 | } 245 | 246 | @Override 247 | public void onAnimationEnd(Animator animation) { 248 | if (!mCanceling) { 249 | setStateInternal(mEndState); 250 | } 251 | } 252 | } 253 | } 254 | -------------------------------------------------------------------------------- /springheader/src/main/java/com/loopeer/springheader/ViewOffsetBehavior.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.loopeer.springheader; 18 | 19 | import android.content.Context; 20 | import android.support.design.widget.CoordinatorLayout; 21 | import android.util.AttributeSet; 22 | import android.view.View; 23 | 24 | /** 25 | * Behavior will automatically sets up a {@link ViewOffsetHelper} on a {@link View}. 26 | */ 27 | class ViewOffsetBehavior extends CoordinatorLayout.Behavior { 28 | 29 | private ViewOffsetHelper mViewOffsetHelper; 30 | 31 | private int mTempTopBottomOffset = 0; 32 | private int mTempLeftRightOffset = 0; 33 | 34 | public ViewOffsetBehavior() {} 35 | 36 | public ViewOffsetBehavior(Context context, AttributeSet attrs) { 37 | super(context, attrs); 38 | } 39 | 40 | @Override 41 | public boolean onLayoutChild(CoordinatorLayout parent, V child, int layoutDirection) { 42 | // First let the parent lay it out 43 | parent.onLayoutChild(child, layoutDirection); 44 | 45 | if (mViewOffsetHelper == null) { 46 | mViewOffsetHelper = new ViewOffsetHelper(child); 47 | } 48 | mViewOffsetHelper.onViewLayout(); 49 | 50 | if (mTempTopBottomOffset != 0) { 51 | mViewOffsetHelper.setTopAndBottomOffset(mTempTopBottomOffset); 52 | mTempTopBottomOffset = 0; 53 | } 54 | if (mTempLeftRightOffset != 0) { 55 | mViewOffsetHelper.setLeftAndRightOffset(mTempLeftRightOffset); 56 | mTempLeftRightOffset = 0; 57 | } 58 | 59 | return true; 60 | } 61 | 62 | public boolean setTopAndBottomOffset(int offset) { 63 | if (mViewOffsetHelper != null) { 64 | return mViewOffsetHelper.setTopAndBottomOffset(offset); 65 | } else { 66 | mTempTopBottomOffset = offset; 67 | } 68 | return false; 69 | } 70 | 71 | public boolean setLeftAndRightOffset(int offset) { 72 | if (mViewOffsetHelper != null) { 73 | return mViewOffsetHelper.setLeftAndRightOffset(offset); 74 | } else { 75 | mTempLeftRightOffset = offset; 76 | } 77 | return false; 78 | } 79 | 80 | public int getTopAndBottomOffset() { 81 | return mViewOffsetHelper != null ? mViewOffsetHelper.getTopAndBottomOffset() : 0; 82 | } 83 | 84 | public int getLeftAndRightOffset() { 85 | return mViewOffsetHelper != null ? mViewOffsetHelper.getLeftAndRightOffset() : 0; 86 | } 87 | } -------------------------------------------------------------------------------- /springheader/src/main/java/com/loopeer/springheader/ViewOffsetHelper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.loopeer.springheader; 18 | 19 | import android.os.Build; 20 | import android.support.v4.view.ViewCompat; 21 | import android.view.View; 22 | import android.view.ViewParent; 23 | 24 | /** 25 | * Utility helper for moving a {@link View} around using 26 | * {@link View#offsetLeftAndRight(int)} and 27 | * {@link View#offsetTopAndBottom(int)}. 28 | *

29 | * Also the setting of absolute offsets (similar to translationX/Y), rather than additive 30 | * offsets. 31 | */ 32 | class ViewOffsetHelper { 33 | 34 | private final View mView; 35 | 36 | private int mLayoutTop; 37 | private int mLayoutLeft; 38 | private int mOffsetTop; 39 | private int mOffsetLeft; 40 | 41 | public ViewOffsetHelper(View view) { 42 | mView = view; 43 | } 44 | 45 | public void onViewLayout() { 46 | // Now grab the intended top 47 | mLayoutTop = mView.getTop(); 48 | mLayoutLeft = mView.getLeft(); 49 | 50 | // And offset it as needed 51 | updateOffsets(); 52 | } 53 | 54 | private void updateOffsets() { 55 | ViewCompat.offsetTopAndBottom(mView, mOffsetTop - (mView.getTop() - mLayoutTop)); 56 | ViewCompat.offsetLeftAndRight(mView, mOffsetLeft - (mView.getLeft() - mLayoutLeft)); 57 | 58 | // Manually invalidate the view and parent to make sure we get drawn pre-M 59 | if (Build.VERSION.SDK_INT < 23) { 60 | tickleInvalidationFlag(mView); 61 | final ViewParent vp = mView.getParent(); 62 | if (vp instanceof View) { 63 | tickleInvalidationFlag((View) vp); 64 | } 65 | } 66 | } 67 | 68 | private static void tickleInvalidationFlag(View view) { 69 | final float x = ViewCompat.getTranslationX(view); 70 | ViewCompat.setTranslationY(view, x + 1); 71 | ViewCompat.setTranslationY(view, x); 72 | } 73 | 74 | /** 75 | * Set the top and bottom offset for this {@link android.support.design.widget.ViewOffsetHelper}'s view. 76 | * 77 | * @param offset the offset in px. 78 | * @return true if the offset has changed 79 | */ 80 | public boolean setTopAndBottomOffset(int offset) { 81 | if (mOffsetTop != offset) { 82 | mOffsetTop = offset; 83 | updateOffsets(); 84 | return true; 85 | } 86 | return false; 87 | } 88 | 89 | /** 90 | * Set the left and right offset for this {@link android.support.design.widget.ViewOffsetHelper}'s view. 91 | * 92 | * @param offset the offset in px. 93 | * @return true if the offset has changed 94 | */ 95 | public boolean setLeftAndRightOffset(int offset) { 96 | if (mOffsetLeft != offset) { 97 | mOffsetLeft = offset; 98 | updateOffsets(); 99 | return true; 100 | } 101 | return false; 102 | } 103 | 104 | public int getTopAndBottomOffset() { 105 | return mOffsetTop; 106 | } 107 | 108 | public int getLeftAndRightOffset() { 109 | return mOffsetLeft; 110 | } 111 | } -------------------------------------------------------------------------------- /springheader/src/main/res/layout/refresh_header_simple.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 12 | 13 | 18 | 19 | -------------------------------------------------------------------------------- /springheader/src/main/res/values/attrs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /springheader/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | SpringHeader 3 | 4 | com.loopeer.springheader.SpringHeaderBehavior 5 | com.loopeer.springheader.DependentViewBehavior 6 | 7 | 下拉刷新 8 | 释放刷新 9 | 正在加载 10 | 11 | --------------------------------------------------------------------------------