├── .idea ├── .name ├── copyright │ └── profiles_settings.xml ├── encodings.xml ├── vcs.xml ├── inspectionProfiles │ ├── profiles_settings.xml │ └── Project_Default.xml ├── modules.xml ├── runConfigurations.xml ├── compiler.xml ├── gradle.xml └── misc.xml ├── app ├── .gitignore ├── src │ ├── main │ │ ├── res │ │ │ ├── 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 │ │ │ │ ├── strings.xml │ │ │ │ ├── colors.xml │ │ │ │ ├── dimens.xml │ │ │ │ └── styles.xml │ │ │ ├── values-w820dp │ │ │ │ └── dimens.xml │ │ │ ├── values-v21 │ │ │ │ └── styles.xml │ │ │ ├── values-v19 │ │ │ │ └── styles.xml │ │ │ └── layout │ │ │ │ ├── activity_second.xml │ │ │ │ └── activity_main.xml │ │ ├── java │ │ │ └── me │ │ │ │ └── majiajie │ │ │ │ └── swipebacktest │ │ │ │ ├── MyApplication.java │ │ │ │ ├── activity │ │ │ │ ├── SecondActivity.java │ │ │ │ ├── BaseActivity.java │ │ │ │ └── MainActivity.java │ │ │ │ ├── adapter │ │ │ │ └── FragmentViewPagerAdapter.java │ │ │ │ ├── view │ │ │ │ └── MyViewPager.java │ │ │ │ └── fragment │ │ │ │ └── AFragment.java │ │ └── AndroidManifest.xml │ └── androidTest │ │ └── java │ │ └── me │ │ └── majiajie │ │ └── swipebacktest │ │ └── ApplicationTest.java ├── proguard-rules.pro └── build.gradle ├── swipe-back ├── .gitignore ├── src │ ├── main │ │ ├── res │ │ │ ├── values │ │ │ │ ├── strings.xml │ │ │ │ └── styles.xml │ │ │ ├── drawable │ │ │ │ └── swipeback_shadow_left.png │ │ │ └── anim │ │ │ │ ├── swipeback_activity_close_exit.xml │ │ │ │ ├── swipeback_activity_open_enter.xml │ │ │ │ ├── swipeback_activity_close_enter.xml │ │ │ │ └── swipeback_activity_open_exit.xml │ │ ├── AndroidManifest.xml │ │ └── java │ │ │ └── me │ │ │ └── majiajie │ │ │ └── swipeback │ │ │ ├── SwipeBackHelper.java │ │ │ ├── SwipeBackActivity.java │ │ │ ├── SwipeBackPreferenceActivity.java │ │ │ ├── utils │ │ │ ├── ActivityStack.java │ │ │ ├── Utils.java │ │ │ └── ViewDragHelper.java │ │ │ └── SwipeBackLayout.java │ └── androidTest │ │ └── java │ │ └── me │ │ └── majiajie │ │ └── swipeback │ │ └── ApplicationTest.java ├── proguard-rules.pro └── build.gradle ├── settings.gradle ├── images └── swipeback.png ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── .gitignore ├── gradle.properties ├── gradlew.bat ├── README.md ├── gradlew └── LICENSE /.idea/.name: -------------------------------------------------------------------------------- 1 | SwipeBack -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /swipe-back/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app', ':swipe-back' 2 | -------------------------------------------------------------------------------- /images/swipeback.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tyzlmjj/SwipeBack/HEAD/images/swipeback.png -------------------------------------------------------------------------------- /.idea/copyright/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tyzlmjj/SwipeBack/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /swipe-back/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | Swipe-Back 3 | 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/workspace.xml 5 | /.idea/libraries 6 | .DS_Store 7 | /build 8 | /captures 9 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tyzlmjj/SwipeBack/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tyzlmjj/SwipeBack/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tyzlmjj/SwipeBack/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tyzlmjj/SwipeBack/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tyzlmjj/SwipeBack/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /swipe-back/src/main/res/drawable/swipeback_shadow_left.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tyzlmjj/SwipeBack/HEAD/swipe-back/src/main/res/drawable/swipeback_shadow_left.png -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | SwipeBack 3 | Main2Activity 4 | 5 | -------------------------------------------------------------------------------- /.idea/encodings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #3F51B5 4 | #303F9F 5 | #FF4081 6 | 7 | -------------------------------------------------------------------------------- /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.10-all.zip 7 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16dp 4 | 16dp 5 | 16dp 6 | 7 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/Project_Default.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | -------------------------------------------------------------------------------- /swipe-back/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /app/src/main/res/values-w820dp/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 64dp 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values-v21/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 13 | 14 | -------------------------------------------------------------------------------- /app/src/androidTest/java/me/majiajie/swipebacktest/ApplicationTest.java: -------------------------------------------------------------------------------- 1 | package me.majiajie.swipebacktest; 2 | 3 | import android.app.Application; 4 | import android.test.ApplicationTestCase; 5 | 6 | /** 7 | * Testing Fundamentals 8 | */ 9 | public class ApplicationTest extends ApplicationTestCase { 10 | public ApplicationTest() { 11 | super(Application.class); 12 | } 13 | } -------------------------------------------------------------------------------- /app/src/main/java/me/majiajie/swipebacktest/MyApplication.java: -------------------------------------------------------------------------------- 1 | package me.majiajie.swipebacktest; 2 | 3 | 4 | import android.app.Application; 5 | 6 | import me.majiajie.swipeback.utils.ActivityStack; 7 | 8 | public class MyApplication extends Application 9 | { 10 | @Override 11 | public void onCreate() 12 | { 13 | super.onCreate(); 14 | this.registerActivityLifecycleCallbacks(ActivityStack.getInstance()); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /swipe-back/src/androidTest/java/me/majiajie/swipeback/ApplicationTest.java: -------------------------------------------------------------------------------- 1 | package me.majiajie.swipeback; 2 | 3 | import android.app.Application; 4 | import android.test.ApplicationTestCase; 5 | 6 | /** 7 | * Testing Fundamentals 8 | */ 9 | public class ApplicationTest extends ApplicationTestCase { 10 | public ApplicationTest() { 11 | super(Application.class); 12 | } 13 | } -------------------------------------------------------------------------------- /app/src/main/res/values-v19/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 14 | 15 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /swipe-back/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 9 | -------------------------------------------------------------------------------- /.idea/runConfigurations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 12 | -------------------------------------------------------------------------------- /app/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 C:\Users\MJJ\Develop\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 | -------------------------------------------------------------------------------- /swipe-back/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 C:\Users\MJJ\Develop\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 | -------------------------------------------------------------------------------- /.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 23 5 | buildToolsVersion "23.0.3" 6 | 7 | defaultConfig { 8 | applicationId "me.majiajie.swipebacktest" 9 | minSdkVersion 15 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 | lintOptions { 22 | abortOnError false 23 | } 24 | } 25 | 26 | dependencies { 27 | compile 'com.android.support:appcompat-v7:23.4.0' 28 | compile 'me.majiajie:pager-bottom-tab-strip:1.0.0' 29 | compile project(':swipe-back') 30 | } 31 | -------------------------------------------------------------------------------- /app/src/main/java/me/majiajie/swipebacktest/activity/SecondActivity.java: -------------------------------------------------------------------------------- 1 | package me.majiajie.swipebacktest.activity; 2 | 3 | import android.content.Intent; 4 | import android.os.Bundle; 5 | import android.view.View; 6 | 7 | import me.majiajie.swipebacktest.R; 8 | 9 | public class SecondActivity extends BaseActivity { 10 | 11 | @Override 12 | protected void onCreate(Bundle savedInstanceState) 13 | { 14 | super.onCreate(savedInstanceState); 15 | setContentView(R.layout.activity_second); 16 | 17 | initToolbar(R.id.toolbar); 18 | 19 | if(getSupportActionBar() != null) 20 | { 21 | getSupportActionBar().setDisplayHomeAsUpEnabled(true); 22 | } 23 | } 24 | 25 | public void next(View v) 26 | { 27 | startActivity(new Intent(SecondActivity.this,SecondActivity.class)); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 12 | 19 | 20 | 66 | ``` 67 | 68 | 5.0(API21)以下的styles.xml 69 | ``` 70 | 77 | ``` 78 | 79 | 80 | 81 | ##联系我 82 | 83 | **Email:** tyzl931019@gmail.com 84 | 85 | **QQ**: 809402737 86 | 87 | 关于这个滑动返回的流畅度还有待提高!欢迎加我QQ交流 88 | 89 | ##错误反馈 90 | 91 | 这个库有BUG?请点这里 [Github Issues](https://github.com/tyzlmjj/SwipeBack/issues) 92 | 93 | 94 | 95 | ##LICENSE 96 | 97 | SwipeBack is released under the [Apache 2.0 license](/LICENSE). 98 | ``` 99 | Copyright 2016 MJJ 100 | 101 | Licensed under the Apache License, Version 2.0 (the "License"); 102 | you may not use this file except in compliance with the License. 103 | You may obtain a copy of the License at 104 | 105 | http://www.apache.org/licenses/LICENSE-2.0 106 | 107 | Unless required by applicable law or agreed to in writing, software 108 | distributed under the License is distributed on an "AS IS" BASIS, 109 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 110 | See the License for the specific language governing permissions and 111 | limitations under the License. 112 | ``` 113 | -------------------------------------------------------------------------------- /app/src/main/java/me/majiajie/swipebacktest/activity/MainActivity.java: -------------------------------------------------------------------------------- 1 | package me.majiajie.swipebacktest.activity; 2 | 3 | import android.content.Intent; 4 | import android.os.Bundle; 5 | import android.support.v4.app.Fragment; 6 | import android.support.v4.view.ViewPager; 7 | import android.view.View; 8 | 9 | import java.util.ArrayList; 10 | import java.util.List; 11 | 12 | import me.majiajie.pagerbottomtabstrip.Controller; 13 | import me.majiajie.pagerbottomtabstrip.PagerBottomTabLayout; 14 | import me.majiajie.pagerbottomtabstrip.listener.OnTabItemSelectListener; 15 | import me.majiajie.swipebacktest.R; 16 | import me.majiajie.swipebacktest.adapter.FragmentViewPagerAdapter; 17 | import me.majiajie.swipebacktest.fragment.AFragment; 18 | 19 | public class MainActivity extends BaseActivity 20 | { 21 | private Controller mController; 22 | 23 | private ViewPager mViewPager; 24 | 25 | @Override 26 | protected void onCreate(Bundle savedInstanceState) 27 | { 28 | super.onCreate(savedInstanceState); 29 | setContentView(R.layout.activity_main); 30 | 31 | initToolbar(R.id.toolbar); 32 | 33 | initBottomTab(); 34 | 35 | initViewPager(); 36 | 37 | initEvent(); 38 | 39 | setSwipeBackEnable(false);//设置不能边缘滑动返回 40 | } 41 | 42 | private void initBottomTab() 43 | { 44 | PagerBottomTabLayout bottomTabLayout = (PagerBottomTabLayout) findViewById(R.id.tab); 45 | 46 | mController = bottomTabLayout.builder() 47 | .addTabItem(android.R.drawable.ic_menu_camera, "相机") 48 | .addTabItem(android.R.drawable.ic_menu_compass, "位置") 49 | .addTabItem(android.R.drawable.ic_menu_search, "搜索") 50 | .addTabItem(android.R.drawable.ic_menu_help, "帮助") 51 | .build(); 52 | } 53 | 54 | private void initViewPager() 55 | { 56 | List fragmentList = new ArrayList<>(); 57 | fragmentList.add(AFragment.newInstance("1")); 58 | fragmentList.add(AFragment.newInstance("2")); 59 | fragmentList.add(AFragment.newInstance("3")); 60 | fragmentList.add(AFragment.newInstance("4")); 61 | 62 | mViewPager = (ViewPager) findViewById(R.id.viewPager); 63 | if(mViewPager != null) 64 | { 65 | mViewPager.setAdapter(new FragmentViewPagerAdapter(getSupportFragmentManager(), fragmentList)); 66 | } 67 | } 68 | 69 | private void initEvent() 70 | { 71 | mController.addTabItemClickListener(new OnTabItemSelectListener() 72 | { 73 | @Override 74 | public void onSelected(int index, Object tag) 75 | { 76 | mViewPager.setCurrentItem(index,false); 77 | } 78 | 79 | @Override 80 | public void onRepeatClick(int index, Object tag) 81 | { 82 | //重复选中 83 | } 84 | }); 85 | 86 | } 87 | 88 | public void next(View v) 89 | { 90 | startActivity(new Intent(MainActivity.this,SecondActivity.class)); 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /swipe-back/src/main/java/me/majiajie/swipeback/SwipeBackLayout.java: -------------------------------------------------------------------------------- 1 | package me.majiajie.swipeback; 2 | 3 | import android.animation.ObjectAnimator; 4 | import android.app.Activity; 5 | import android.content.Context; 6 | import android.content.res.TypedArray; 7 | import android.graphics.Canvas; 8 | import android.graphics.Rect; 9 | import android.graphics.drawable.Drawable; 10 | import android.support.v4.content.ContextCompat; 11 | import android.support.v4.view.ViewCompat; 12 | import android.util.AttributeSet; 13 | import android.view.MotionEvent; 14 | import android.view.View; 15 | import android.view.ViewGroup; 16 | import android.widget.FrameLayout; 17 | 18 | import me.majiajie.swipeback.utils.ActivityStack; 19 | import me.majiajie.swipeback.utils.Utils; 20 | import me.majiajie.swipeback.utils.ViewDragHelper; 21 | 22 | public class SwipeBackLayout extends FrameLayout 23 | { 24 | /** 25 | * 滑动销毁距离界限 26 | */ 27 | private static final float DEFAULT_SCROLL_THRESHOLD = 0.5f; 28 | 29 | /** 30 | * 滑动销毁速度界限 31 | */ 32 | private static final float DEFAULT_VELOCITY_THRESHOLD = 500f; 33 | 34 | /** 35 | * 最大透明度 36 | */ 37 | private static final int FULL_ALPHA = 255; 38 | 39 | /** 40 | * 最小滑动速度 41 | */ 42 | private static final int MIN_FLING_VELOCITY = 200; 43 | 44 | 45 | private ViewDragHelper mViewDragHelper; 46 | 47 | private Activity mActivity; 48 | 49 | private View mContentView; 50 | 51 | 52 | /** 53 | * 记录左边移动的像素值 54 | */ 55 | private int mContentLeft; 56 | 57 | /** 58 | * 当前滑动范围 [0,1) 59 | */ 60 | private float mScrollPercent; 61 | 62 | /** 63 | * 阴影 64 | */ 65 | private Drawable mShadowLeft; 66 | 67 | /** 68 | * 记录阴影透明比例 [0,1] 69 | */ 70 | private float mScrimOpacity; 71 | 72 | private Rect mTmpRect = new Rect(); 73 | 74 | /** 75 | * 判断是否正在执行onLayout方法 76 | */ 77 | private boolean mInLayout; 78 | 79 | /** 80 | * 设置是否可滑动 81 | */ 82 | private boolean CanSwipeBack = true; 83 | 84 | /** 85 | * 判断背景Activity是否启动进入动画 86 | */ 87 | private boolean EnterAnimRunning = false; 88 | 89 | /** 90 | * 进入动画(只在释放手指时使用) 91 | */ 92 | private ObjectAnimator mEnterAnim; 93 | 94 | public SwipeBackLayout(Context context) { 95 | super(context); 96 | init(context); 97 | } 98 | 99 | public SwipeBackLayout(Context context, AttributeSet attrs) { 100 | super(context, attrs); 101 | init(context); 102 | } 103 | 104 | public SwipeBackLayout(Context context, AttributeSet attrs, int defStyleAttr) { 105 | super(context, attrs, defStyleAttr); 106 | init(context); 107 | } 108 | 109 | private void init(Context context) 110 | { 111 | mViewDragHelper = ViewDragHelper.create(SwipeBackLayout.this, new ViewDragCallback()); 112 | mViewDragHelper.setEdgeTrackingEnabled(ViewDragHelper.EDGE_LEFT); 113 | 114 | final float density = getResources().getDisplayMetrics().density; 115 | final float minVel = MIN_FLING_VELOCITY * density; 116 | mViewDragHelper.setMinVelocity(minVel); 117 | mViewDragHelper.setMaxVelocity(minVel * 2f); 118 | 119 | mShadowLeft = ContextCompat.getDrawable(context,R.drawable.swipeback_shadow_left); 120 | } 121 | 122 | @Override 123 | protected void onLayout(boolean changed, int left, int top, int right, int bottom) 124 | { 125 | mInLayout = true; 126 | if (mContentView != null) 127 | { 128 | mContentView.layout(mContentLeft, top, 129 | mContentLeft + mContentView.getMeasuredWidth(), 130 | mContentView.getMeasuredHeight()); 131 | } 132 | mInLayout = false; 133 | } 134 | 135 | @Override 136 | public void requestLayout() 137 | { 138 | if (!mInLayout) 139 | { 140 | super.requestLayout(); 141 | } 142 | } 143 | 144 | @Override 145 | protected boolean drawChild(Canvas canvas, View child, long drawingTime) 146 | { 147 | final boolean drawContent = child == mContentView; 148 | 149 | boolean ret = super.drawChild(canvas, child, drawingTime); 150 | if (mScrimOpacity > 0 && drawContent 151 | && mViewDragHelper.getViewDragState() != ViewDragHelper.STATE_IDLE) 152 | { 153 | drawShadow(canvas, child); 154 | } 155 | return ret; 156 | } 157 | 158 | /** 159 | * 画阴影 160 | */ 161 | private void drawShadow(Canvas canvas, View child) 162 | { 163 | final Rect childRect = mTmpRect; 164 | child.getHitRect(childRect); 165 | 166 | mShadowLeft.setBounds(childRect.left - mShadowLeft.getIntrinsicWidth(), childRect.top, 167 | childRect.left, childRect.bottom); 168 | mShadowLeft.setAlpha((int) (mScrimOpacity * FULL_ALPHA)); 169 | mShadowLeft.draw(canvas); 170 | } 171 | 172 | @Override 173 | public void computeScroll() 174 | { 175 | mScrimOpacity = 1 - mScrollPercent; 176 | if (mViewDragHelper.continueSettling(true)) 177 | { 178 | ViewCompat.postInvalidateOnAnimation(this); 179 | } 180 | } 181 | 182 | @Override 183 | public boolean onInterceptTouchEvent(MotionEvent event) 184 | { 185 | try 186 | { 187 | return mViewDragHelper.shouldInterceptTouchEvent(event); 188 | } 189 | catch (ArrayIndexOutOfBoundsException e) 190 | { 191 | return false; 192 | } 193 | } 194 | 195 | @Override 196 | public boolean onTouchEvent(MotionEvent event) 197 | { 198 | mViewDragHelper.processTouchEvent(event); 199 | return true; 200 | } 201 | 202 | /** 203 | * 将View添加到Activity 204 | */ 205 | public void attachToActivity(Activity activity) 206 | { 207 | mActivity = activity; 208 | TypedArray a = activity.getTheme().obtainStyledAttributes(new int[]{ 209 | android.R.attr.windowBackground 210 | }); 211 | int background = a.getResourceId(0, 0); 212 | a.recycle(); 213 | 214 | ViewGroup decor = (ViewGroup) activity.getWindow().getDecorView(); 215 | ViewGroup decorChild = (ViewGroup) decor.getChildAt(0); 216 | decorChild.setBackgroundResource(background); 217 | decor.removeView(decorChild); 218 | addView(decorChild); 219 | setContentView(decorChild); 220 | decor.addView(this); 221 | } 222 | 223 | /** 224 | * 设置是否可以滑动返回 225 | */ 226 | public void setSwipeBackEnable(boolean enable) 227 | { 228 | CanSwipeBack = enable; 229 | } 230 | 231 | /** 232 | * 启动进入动画 233 | */ 234 | public void startEnterAnim() 235 | { 236 | if (mContentView != null) 237 | { 238 | ObjectAnimator anim = ObjectAnimator 239 | .ofFloat(mContentView,"TranslationX",mContentView.getTranslationX(),0f); 240 | 241 | anim.setDuration((long) (125*mScrimOpacity)); 242 | 243 | mEnterAnim = anim; 244 | mEnterAnim.start(); 245 | } 246 | } 247 | 248 | /** 249 | * 回复界面的平移到初始位置 250 | */ 251 | public void recovery() 252 | { 253 | if(mEnterAnim != null && mEnterAnim.isRunning()) 254 | { 255 | mEnterAnim.end(); 256 | } 257 | else 258 | { 259 | mContentView.setTranslationX(0); 260 | } 261 | } 262 | 263 | protected View getContentView() 264 | { 265 | return mContentView; 266 | } 267 | 268 | private void setContentView(ViewGroup decorChild) 269 | { 270 | mContentView = decorChild; 271 | } 272 | 273 | private class ViewDragCallback extends ViewDragHelper.Callback 274 | { 275 | @Override 276 | public boolean tryCaptureView(View child, int pointerId) 277 | { 278 | boolean ret = mViewDragHelper.isEdgeTouched(ViewDragHelper.EDGE_LEFT, pointerId); 279 | if (CanSwipeBack && ret) 280 | { 281 | Utils.convertActivityToTranslucent(mActivity); 282 | return true; 283 | } 284 | return false; 285 | } 286 | 287 | @Override 288 | public int getViewHorizontalDragRange(View child) 289 | { 290 | return CanSwipeBack?ViewDragHelper.EDGE_LEFT:0; 291 | } 292 | 293 | @Override 294 | public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) 295 | { 296 | super.onViewPositionChanged(changedView, left, top, dx, dy); 297 | 298 | if(changedView == mContentView) 299 | { 300 | mScrollPercent = Math.abs((float) left 301 | / (mContentView.getWidth() + mShadowLeft.getIntrinsicWidth())); 302 | 303 | mContentLeft = left; 304 | 305 | //未执行动画就平移 306 | if(!EnterAnimRunning) 307 | { 308 | moveBackgroundActivity(); 309 | } 310 | 311 | invalidate(); 312 | 313 | if (mScrollPercent >= 1 && !mActivity.isFinishing()) 314 | { 315 | mActivity.finish(); 316 | } 317 | } 318 | } 319 | 320 | @Override 321 | public void onViewReleased(View releasedChild, float xvel, float yvel) 322 | { 323 | final int childWidth = releasedChild.getWidth(); 324 | 325 | int left = 0, top = 0; 326 | 327 | if(xvel > DEFAULT_VELOCITY_THRESHOLD || mScrollPercent > DEFAULT_SCROLL_THRESHOLD) 328 | { 329 | left = childWidth + mShadowLeft.getIntrinsicWidth(); 330 | mViewDragHelper.settleCapturedViewAt(left, top); 331 | 332 | if(mScrimOpacity < 0.85f) 333 | { 334 | startAnimOfBackgroundActivity(); 335 | } 336 | } 337 | else 338 | { 339 | left = 0; 340 | mViewDragHelper.settleCapturedViewAt(left, top); 341 | } 342 | invalidate(); 343 | } 344 | 345 | @Override 346 | public int clampViewPositionHorizontal(View child, int left, int dx) 347 | { 348 | int ret = Math.min(child.getWidth(), Math.max(left, 0)); 349 | return ret; 350 | } 351 | 352 | @Override 353 | public void onViewDragStateChanged(int state) 354 | { 355 | super.onViewDragStateChanged(state); 356 | 357 | if(state == ViewDragHelper.STATE_IDLE && mScrollPercent < 1f) 358 | { 359 | Utils.convertActivotyFromTranslucent(mActivity); 360 | } 361 | } 362 | } 363 | 364 | 365 | /** 366 | * 背景Activity开始进入动画 367 | */ 368 | private void startAnimOfBackgroundActivity() 369 | { 370 | Activity activity = ActivityStack.getInstance().getBackActivity(); 371 | if(activity instanceof SwipeBackActivity) 372 | { 373 | EnterAnimRunning = true; 374 | SwipeBackLayout swipeBackLayout = ((SwipeBackActivity) activity).getSwipeBackLayout(); 375 | swipeBackLayout.startEnterAnim(); 376 | } 377 | } 378 | 379 | /** 380 | * 移动背景Activity 381 | */ 382 | private void moveBackgroundActivity() 383 | { 384 | Activity activity = ActivityStack.getInstance().getBackActivity(); 385 | if(activity instanceof SwipeBackActivity) 386 | { 387 | View view = ((SwipeBackActivity) activity).getSwipeBackLayout().getContentView(); 388 | 389 | if(view != null) 390 | { 391 | int width = view.getWidth(); 392 | view.setTranslationX(-width*0.3f*Math.max(0f,mScrimOpacity-0.15f)); 393 | } 394 | } 395 | } 396 | } 397 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /swipe-back/src/main/java/me/majiajie/swipeback/utils/ViewDragHelper.java: -------------------------------------------------------------------------------- 1 | package me.majiajie.swipeback.utils; 2 | 3 | import android.content.Context; 4 | import android.support.v4.view.MotionEventCompat; 5 | import android.support.v4.view.VelocityTrackerCompat; 6 | import android.support.v4.view.ViewCompat; 7 | import android.support.v4.widget.ScrollerCompat; 8 | import android.util.Log; 9 | import android.view.MotionEvent; 10 | import android.view.VelocityTracker; 11 | import android.view.View; 12 | import android.view.ViewConfiguration; 13 | import android.view.ViewGroup; 14 | import android.view.animation.Interpolator; 15 | 16 | import java.util.Arrays; 17 | 18 | 19 | /** 20 | * ViewDragHelper is a utility class for writing custom ViewGroups. It offers a number 21 | * of useful operations and state tracking for allowing a user to drag and reposition 22 | * views within their parent ViewGroup. 23 | */ 24 | public class ViewDragHelper 25 | { 26 | private static final String TAG = "ViewDragHelper"; 27 | 28 | /** 29 | * A null/invalid pointer ID. 30 | */ 31 | public static final int INVALID_POINTER = -1; 32 | 33 | /** 34 | * A view is not currently being dragged or animating as a result of a fling/snap. 35 | */ 36 | public static final int STATE_IDLE = 0; 37 | 38 | /** 39 | * A view is currently being dragged. The position is currently changing as a result 40 | * of user input or simulated user input. 41 | */ 42 | public static final int STATE_DRAGGING = 1; 43 | 44 | /** 45 | * A view is currently settling into place as a result of a fling or 46 | * predefined non-interactive motion. 47 | */ 48 | public static final int STATE_SETTLING = 2; 49 | 50 | /** 51 | * Edge flag indicating that the left edge should be affected. 52 | */ 53 | public static final int EDGE_LEFT = 1 << 0; 54 | 55 | /** 56 | * Edge flag indicating that the right edge should be affected. 57 | */ 58 | public static final int EDGE_RIGHT = 1 << 1; 59 | 60 | /** 61 | * Edge flag indicating that the top edge should be affected. 62 | */ 63 | public static final int EDGE_TOP = 1 << 2; 64 | 65 | /** 66 | * Edge flag indicating that the bottom edge should be affected. 67 | */ 68 | public static final int EDGE_BOTTOM = 1 << 3; 69 | 70 | /** 71 | * Edge flag set indicating all edges should be affected. 72 | */ 73 | public static final int EDGE_ALL = EDGE_LEFT | EDGE_TOP | EDGE_RIGHT | EDGE_BOTTOM; 74 | 75 | /** 76 | * Indicates that a check should occur along the horizontal axis 77 | */ 78 | public static final int DIRECTION_HORIZONTAL = 1 << 0; 79 | 80 | /** 81 | * Indicates that a check should occur along the vertical axis 82 | */ 83 | public static final int DIRECTION_VERTICAL = 1 << 1; 84 | 85 | /** 86 | * Indicates that a check should occur along all axes 87 | */ 88 | public static final int DIRECTION_ALL = DIRECTION_HORIZONTAL | DIRECTION_VERTICAL; 89 | 90 | private static final int EDGE_SIZE = 20; // dp 91 | 92 | private static final int BASE_SETTLE_DURATION = 256; // ms 93 | private static final int MAX_SETTLE_DURATION = 600; // ms 94 | 95 | // Current drag state; idle, dragging or settling 96 | private int mDragState; 97 | 98 | // Distance to travel before a drag may begin 99 | private int mTouchSlop; 100 | 101 | // Last known position/pointer tracking 102 | private int mActivePointerId = INVALID_POINTER; 103 | private float[] mInitialMotionX; 104 | private float[] mInitialMotionY; 105 | private float[] mLastMotionX; 106 | private float[] mLastMotionY; 107 | private int[] mInitialEdgesTouched; 108 | private int[] mEdgeDragsInProgress; 109 | private int[] mEdgeDragsLocked; 110 | private int mPointersDown; 111 | 112 | private VelocityTracker mVelocityTracker; 113 | private float mMaxVelocity; 114 | private float mMinVelocity; 115 | 116 | private int mEdgeSize; 117 | private int mTrackingEdges; 118 | 119 | private ScrollerCompat mScroller; 120 | 121 | private final Callback mCallback; 122 | 123 | private View mCapturedView; 124 | private boolean mReleaseInProgress; 125 | 126 | private final ViewGroup mParentView; 127 | 128 | /** 129 | * A Callback is used as a communication channel with the ViewDragHelper back to the 130 | * parent view using it. on*methods are invoked on siginficant events and several 131 | * accessor methods are expected to provide the ViewDragHelper with more information 132 | * about the state of the parent view upon request. The callback also makes decisions 133 | * governing the range and draggability of child views. 134 | */ 135 | public static abstract class Callback { 136 | /** 137 | * Called when the drag state changes. See the STATE_* constants 138 | * for more information. 139 | * 140 | * @param state The new drag state 141 | * 142 | * @see #STATE_IDLE 143 | * @see #STATE_DRAGGING 144 | * @see #STATE_SETTLING 145 | */ 146 | public void onViewDragStateChanged(int state) {} 147 | 148 | /** 149 | * Called when the captured view's position changes as the result of a drag or settle. 150 | * 151 | * @param changedView View whose position changed 152 | * @param left New X coordinate of the left edge of the view 153 | * @param top New Y coordinate of the top edge of the view 154 | * @param dx Change in X position from the last call 155 | * @param dy Change in Y position from the last call 156 | */ 157 | public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {} 158 | 159 | /** 160 | * Called when a child view is captured for dragging or settling. The ID of the pointer 161 | * currently dragging the captured view is supplied. If activePointerId is 162 | * identified as {@link #INVALID_POINTER} the capture is programmatic instead of 163 | * pointer-initiated. 164 | * 165 | * @param capturedChild Child view that was captured 166 | * @param activePointerId Pointer id tracking the child capture 167 | */ 168 | public void onViewCaptured(View capturedChild, int activePointerId) {} 169 | 170 | /** 171 | * Called when the child view is no longer being actively dragged. 172 | * The fling velocity is also supplied, if relevant. The velocity values may 173 | * be clamped to system minimums or maximums. 174 | * 175 | *

Calling code may decide to fling or otherwise release the view to let it 176 | * settle into place. It should do so using {@link #settleCapturedViewAt(int, int)} 177 | * or {@link #flingCapturedView(int, int, int, int)}. If the Callback invokes 178 | * one of these methods, the ViewDragHelper will enter {@link #STATE_SETTLING} 179 | * and the view capture will not fully end until it comes to a complete stop. 180 | * If neither of these methods is invoked before onViewReleased returns, 181 | * the view will stop in place and the ViewDragHelper will return to 182 | * {@link #STATE_IDLE}.

183 | * 184 | * @param releasedChild The captured child view now being released 185 | * @param xvel X velocity of the pointer as it left the screen in pixels per second. 186 | * @param yvel Y velocity of the pointer as it left the screen in pixels per second. 187 | */ 188 | public void onViewReleased(View releasedChild, float xvel, float yvel) {} 189 | 190 | /** 191 | * Called when one of the subscribed edges in the parent view has been touched 192 | * by the user while no child view is currently captured. 193 | * 194 | * @param edgeFlags A combination of edge flags describing the edge(s) currently touched 195 | * @param pointerId ID of the pointer touching the described edge(s) 196 | * @see #EDGE_LEFT 197 | * @see #EDGE_TOP 198 | * @see #EDGE_RIGHT 199 | * @see #EDGE_BOTTOM 200 | */ 201 | public void onEdgeTouched(int edgeFlags, int pointerId) {} 202 | 203 | /** 204 | * Called when the given edge may become locked. This can happen if an edge drag 205 | * was preliminarily rejected before beginning, but after {@link #onEdgeTouched(int, int)} 206 | * was called. This method should return true to lock this edge or false to leave it 207 | * unlocked. The default behavior is to leave edges unlocked. 208 | * 209 | * @param edgeFlags A combination of edge flags describing the edge(s) locked 210 | * @return true to lock the edge, false to leave it unlocked 211 | */ 212 | public boolean onEdgeLock(int edgeFlags) { 213 | return false; 214 | } 215 | 216 | /** 217 | * Called when the user has started a deliberate drag away from one 218 | * of the subscribed edges in the parent view while no child view is currently captured. 219 | * 220 | * @param edgeFlags A combination of edge flags describing the edge(s) dragged 221 | * @param pointerId ID of the pointer touching the described edge(s) 222 | * @see #EDGE_LEFT 223 | * @see #EDGE_TOP 224 | * @see #EDGE_RIGHT 225 | * @see #EDGE_BOTTOM 226 | */ 227 | public void onEdgeDragStarted(int edgeFlags, int pointerId) {} 228 | 229 | /** 230 | * Called to determine the Z-order of child views. 231 | * 232 | * @param index the ordered position to query for 233 | * @return index of the view that should be ordered at position index 234 | */ 235 | public int getOrderedChildIndex(int index) { 236 | return index; 237 | } 238 | 239 | /** 240 | * Return the magnitude of a draggable child view's horizontal range of motion in pixels. 241 | * This method should return 0 for views that cannot move horizontally. 242 | * 243 | * @param child Child view to check 244 | * @return range of horizontal motion in pixels 245 | */ 246 | public int getViewHorizontalDragRange(View child) { 247 | return 0; 248 | } 249 | 250 | /** 251 | * Return the magnitude of a draggable child view's vertical range of motion in pixels. 252 | * This method should return 0 for views that cannot move vertically. 253 | * 254 | * @param child Child view to check 255 | * @return range of vertical motion in pixels 256 | */ 257 | public int getViewVerticalDragRange(View child) { 258 | return 0; 259 | } 260 | 261 | /** 262 | * Called when the user's input indicates that they want to capture the given child view 263 | * with the pointer indicated by pointerId. The callback should return true if the user 264 | * is permitted to drag the given view with the indicated pointer. 265 | * 266 | *

ViewDragHelper may call this method multiple times for the same view even if 267 | * the view is already captured; this indicates that a new pointer is trying to take 268 | * control of the view.

269 | * 270 | *

If this method returns true, a call to {@link #onViewCaptured(android.view.View, int)} 271 | * will follow if the capture is successful.

272 | * 273 | * @param child Child the user is attempting to capture 274 | * @param pointerId ID of the pointer attempting the capture 275 | * @return true if capture should be allowed, false otherwise 276 | */ 277 | public abstract boolean tryCaptureView(View child, int pointerId); 278 | 279 | /** 280 | * Restrict the motion of the dragged child view along the horizontal axis. 281 | * The default implementation does not allow horizontal motion; the extending 282 | * class must override this method and provide the desired clamping. 283 | * 284 | * 285 | * @param child Child view being dragged 286 | * @param left Attempted motion along the X axis 287 | * @param dx Proposed change in position for left 288 | * @return The new clamped position for left 289 | */ 290 | public int clampViewPositionHorizontal(View child, int left, int dx) { 291 | return 0; 292 | } 293 | 294 | /** 295 | * Restrict the motion of the dragged child view along the vertical axis. 296 | * The default implementation does not allow vertical motion; the extending 297 | * class must override this method and provide the desired clamping. 298 | * 299 | * 300 | * @param child Child view being dragged 301 | * @param top Attempted motion along the Y axis 302 | * @param dy Proposed change in position for top 303 | * @return The new clamped position for top 304 | */ 305 | public int clampViewPositionVertical(View child, int top, int dy) { 306 | return 0; 307 | } 308 | } 309 | 310 | /** 311 | * Interpolator defining the animation curve for mScroller 312 | */ 313 | private static final Interpolator sInterpolator = new Interpolator() { 314 | public float getInterpolation(float t) { 315 | t -= 1.0f; 316 | return t * t * t * t * t + 1.0f; 317 | } 318 | }; 319 | 320 | private final Runnable mSetIdleRunnable = new Runnable() { 321 | public void run() { 322 | setDragState(STATE_IDLE); 323 | } 324 | }; 325 | 326 | /** 327 | * Factory method to create a new ViewDragHelper. 328 | * 329 | * @param forParent Parent view to monitor 330 | * @param cb Callback to provide information and receive events 331 | * @return a new ViewDragHelper instance 332 | */ 333 | public static ViewDragHelper create(ViewGroup forParent, Callback cb) { 334 | return new ViewDragHelper(forParent.getContext(), forParent, cb); 335 | } 336 | 337 | /** 338 | * Factory method to create a new ViewDragHelper. 339 | * 340 | * @param forParent Parent view to monitor 341 | * @param sensitivity Multiplier for how sensitive the helper should be about detecting 342 | * the start of a drag. Larger values are more sensitive. 1.0f is normal. 343 | * @param cb Callback to provide information and receive events 344 | * @return a new ViewDragHelper instance 345 | */ 346 | public static ViewDragHelper create(ViewGroup forParent, float sensitivity, Callback cb) { 347 | final ViewDragHelper helper = create(forParent, cb); 348 | helper.mTouchSlop = (int) (helper.mTouchSlop * (1 / sensitivity)); 349 | return helper; 350 | } 351 | 352 | /** 353 | * Apps should use ViewDragHelper.create() to get a new instance. 354 | * This will allow VDH to use internal compatibility implementations for different 355 | * platform versions. 356 | * 357 | * @param context Context to initialize config-dependent params from 358 | * @param forParent Parent view to monitor 359 | */ 360 | private ViewDragHelper(Context context, ViewGroup forParent, Callback cb) { 361 | if (forParent == null) { 362 | throw new IllegalArgumentException("Parent view may not be null"); 363 | } 364 | if (cb == null) { 365 | throw new IllegalArgumentException("Callback may not be null"); 366 | } 367 | 368 | mParentView = forParent; 369 | mCallback = cb; 370 | 371 | final ViewConfiguration vc = ViewConfiguration.get(context); 372 | final float density = context.getResources().getDisplayMetrics().density; 373 | mEdgeSize = (int) (EDGE_SIZE * density + 0.5f); 374 | 375 | mTouchSlop = vc.getScaledTouchSlop(); 376 | mMaxVelocity = vc.getScaledMaximumFlingVelocity(); 377 | mMinVelocity = vc.getScaledMinimumFlingVelocity(); 378 | mScroller = ScrollerCompat.create(context, sInterpolator); 379 | } 380 | 381 | /** 382 | * Set the minimum velocity that will be detected as having a magnitude greater than zero 383 | * in pixels per second. Callback methods accepting a velocity will be clamped appropriately. 384 | * 385 | * @param minVel Minimum velocity to detect 386 | */ 387 | public void setMinVelocity(float minVel) { 388 | mMinVelocity = minVel; 389 | } 390 | 391 | /** 392 | * Return the currently configured minimum velocity. Any flings with a magnitude less 393 | * than this value in pixels per second. Callback methods accepting a velocity will receive 394 | * zero as a velocity value if the real detected velocity was below this threshold. 395 | * 396 | * @return the minimum velocity that will be detected 397 | */ 398 | public float getMinVelocity() { 399 | return mMinVelocity; 400 | } 401 | 402 | public void setMaxVelocity(float maxVel) { 403 | mMaxVelocity = maxVel; 404 | } 405 | 406 | public float getMaxVelocity() { 407 | return mMaxVelocity; 408 | } 409 | 410 | /** 411 | * Retrieve the current drag state of this helper. This will return one of 412 | * {@link #STATE_IDLE}, {@link #STATE_DRAGGING} or {@link #STATE_SETTLING}. 413 | * @return The current drag state 414 | */ 415 | public int getViewDragState() { 416 | return mDragState; 417 | } 418 | 419 | /** 420 | * Enable edge tracking for the selected edges of the parent view. 421 | * The callback's {@link Callback#onEdgeTouched(int, int)} and 422 | * {@link Callback#onEdgeDragStarted(int, int)} methods will only be invoked 423 | * for edges for which edge tracking has been enabled. 424 | * 425 | * @param edgeFlags Combination of edge flags describing the edges to watch 426 | * @see #EDGE_LEFT 427 | * @see #EDGE_TOP 428 | * @see #EDGE_RIGHT 429 | * @see #EDGE_BOTTOM 430 | */ 431 | public void setEdgeTrackingEnabled(int edgeFlags) { 432 | mTrackingEdges = edgeFlags; 433 | } 434 | 435 | /** 436 | * Return the size of an edge. This is the range in pixels along the edges of this view 437 | * that will actively detect edge touches or drags if edge tracking is enabled. 438 | * 439 | * @return The size of an edge in pixels 440 | * @see #setEdgeTrackingEnabled(int) 441 | */ 442 | public int getEdgeSize() { 443 | return mEdgeSize; 444 | } 445 | 446 | /** 447 | * Capture a specific child view for dragging within the parent. The callback will be notified 448 | * but {@link Callback#tryCaptureView(android.view.View, int)} will not be asked permission to 449 | * capture this view. 450 | * 451 | * @param childView Child view to capture 452 | * @param activePointerId ID of the pointer that is dragging the captured child view 453 | */ 454 | public void captureChildView(View childView, int activePointerId) { 455 | if (childView.getParent() != mParentView) { 456 | throw new IllegalArgumentException("captureChildView: parameter must be a descendant " + 457 | "of the ViewDragHelper's tracked parent view (" + mParentView + ")"); 458 | } 459 | 460 | mCapturedView = childView; 461 | mActivePointerId = activePointerId; 462 | mCallback.onViewCaptured(childView, activePointerId); 463 | setDragState(STATE_DRAGGING); 464 | } 465 | 466 | /** 467 | * @return The currently captured view, or null if no view has been captured. 468 | */ 469 | public View getCapturedView() { 470 | return mCapturedView; 471 | } 472 | 473 | /** 474 | * @return The ID of the pointer currently dragging the captured view, 475 | * or {@link #INVALID_POINTER}. 476 | */ 477 | public int getActivePointerId() { 478 | return mActivePointerId; 479 | } 480 | 481 | /** 482 | * @return The minimum distance in pixels that the user must travel to initiate a drag 483 | */ 484 | public int getTouchSlop() { 485 | return mTouchSlop; 486 | } 487 | 488 | /** 489 | * The result of a call to this method is equivalent to 490 | * {@link #processTouchEvent(android.view.MotionEvent)} receiving an ACTION_CANCEL event. 491 | */ 492 | public void cancel() { 493 | mActivePointerId = INVALID_POINTER; 494 | clearMotionHistory(); 495 | 496 | if (mVelocityTracker != null) { 497 | mVelocityTracker.recycle(); 498 | mVelocityTracker = null; 499 | } 500 | } 501 | 502 | /** 503 | * {@link #cancel()}, but also abort all motion in progress and snap to the end of any 504 | * animation. 505 | */ 506 | public void abort() { 507 | cancel(); 508 | if (mDragState == STATE_SETTLING) { 509 | final int oldX = mScroller.getCurrX(); 510 | final int oldY = mScroller.getCurrY(); 511 | mScroller.abortAnimation(); 512 | final int newX = mScroller.getCurrX(); 513 | final int newY = mScroller.getCurrY(); 514 | mCallback.onViewPositionChanged(mCapturedView, newX, newY, newX - oldX, newY - oldY); 515 | } 516 | setDragState(STATE_IDLE); 517 | } 518 | 519 | /** 520 | * Animate the view child to the given (left, top) position. 521 | * If this method returns true, the caller should invoke {@link #continueSettling(boolean)} 522 | * on each subsequent frame to continue the motion until it returns false. If this method 523 | * returns false there is no further work to do to complete the movement. 524 | * 525 | *

This operation does not count as a capture event, though {@link #getCapturedView()} 526 | * will still report the sliding view while the slide is in progress.

527 | * 528 | * @param child Child view to capture and animate 529 | * @param finalLeft Final left position of child 530 | * @param finalTop Final top position of child 531 | * @return true if animation should continue through {@link #continueSettling(boolean)} calls 532 | */ 533 | public boolean smoothSlideViewTo(View child, int finalLeft, int finalTop) { 534 | mCapturedView = child; 535 | mActivePointerId = INVALID_POINTER; 536 | 537 | boolean continueSliding = forceSettleCapturedViewAt(finalLeft, finalTop, 0, 0); 538 | if (!continueSliding && mDragState == STATE_IDLE && mCapturedView != null) { 539 | // If we're in an IDLE state to begin with and aren't moving anywhere, we 540 | // end up having a non-null capturedView with an IDLE dragState 541 | mCapturedView = null; 542 | } 543 | 544 | return continueSliding; 545 | } 546 | 547 | /** 548 | * Settle the captured view at the given (left, top) position. 549 | * The appropriate velocity from prior motion will be taken into account. 550 | * If this method returns true, the caller should invoke {@link #continueSettling(boolean)} 551 | * on each subsequent frame to continue the motion until it returns false. If this method 552 | * returns false there is no further work to do to complete the movement. 553 | * 554 | * @param finalLeft Settled left edge position for the captured view 555 | * @param finalTop Settled top edge position for the captured view 556 | * @return true if animation should continue through {@link #continueSettling(boolean)} calls 557 | */ 558 | public boolean settleCapturedViewAt(int finalLeft, int finalTop) { 559 | if (!mReleaseInProgress) { 560 | throw new IllegalStateException("Cannot settleCapturedViewAt outside of a call to " + 561 | "Callback#onViewReleased"); 562 | } 563 | 564 | return forceSettleCapturedViewAt(finalLeft, finalTop, 565 | (int) VelocityTrackerCompat.getXVelocity(mVelocityTracker, mActivePointerId), 566 | (int) VelocityTrackerCompat.getYVelocity(mVelocityTracker, mActivePointerId)); 567 | } 568 | 569 | /** 570 | * Settle the captured view at the given (left, top) position. 571 | * 572 | * @param finalLeft Target left position for the captured view 573 | * @param finalTop Target top position for the captured view 574 | * @param xvel Horizontal velocity 575 | * @param yvel Vertical velocity 576 | * @return true if animation should continue through {@link #continueSettling(boolean)} calls 577 | */ 578 | private boolean forceSettleCapturedViewAt(int finalLeft, int finalTop, int xvel, int yvel) { 579 | final int startLeft = mCapturedView.getLeft(); 580 | final int startTop = mCapturedView.getTop(); 581 | final int dx = finalLeft - startLeft; 582 | final int dy = finalTop - startTop; 583 | 584 | if (dx == 0 && dy == 0) { 585 | // Nothing to do. Send callbacks, be done. 586 | mScroller.abortAnimation(); 587 | setDragState(STATE_IDLE); 588 | return false; 589 | } 590 | 591 | final int duration = computeSettleDuration(mCapturedView, dx, dy, xvel, yvel); 592 | mScroller.startScroll(startLeft, startTop, dx, dy, duration); 593 | 594 | setDragState(STATE_SETTLING); 595 | return true; 596 | } 597 | 598 | private int computeSettleDuration(View child, int dx, int dy, int xvel, int yvel) { 599 | xvel = clampMag(xvel, (int) mMinVelocity, (int) mMaxVelocity); 600 | yvel = clampMag(yvel, (int) mMinVelocity, (int) mMaxVelocity); 601 | final int absDx = Math.abs(dx); 602 | final int absDy = Math.abs(dy); 603 | final int absXVel = Math.abs(xvel); 604 | final int absYVel = Math.abs(yvel); 605 | final int addedVel = absXVel + absYVel; 606 | final int addedDistance = absDx + absDy; 607 | 608 | final float xweight = xvel != 0 ? (float) absXVel / addedVel : 609 | (float) absDx / addedDistance; 610 | final float yweight = yvel != 0 ? (float) absYVel / addedVel : 611 | (float) absDy / addedDistance; 612 | 613 | int xduration = computeAxisDuration(dx, xvel, mCallback.getViewHorizontalDragRange(child)); 614 | int yduration = computeAxisDuration(dy, yvel, mCallback.getViewVerticalDragRange(child)); 615 | 616 | return (int) (xduration * xweight + yduration * yweight); 617 | } 618 | 619 | private int computeAxisDuration(int delta, int velocity, int motionRange) { 620 | if (delta == 0) { 621 | return 0; 622 | } 623 | 624 | final int width = mParentView.getWidth(); 625 | final int halfWidth = width / 2; 626 | final float distanceRatio = Math.min(1f, (float) Math.abs(delta) / width); 627 | final float distance = halfWidth + halfWidth * 628 | distanceInfluenceForSnapDuration(distanceRatio); 629 | 630 | int duration; 631 | velocity = Math.abs(velocity); 632 | if (velocity > 0) { 633 | duration = 4 * Math.round(1000 * Math.abs(distance / velocity)); 634 | } else { 635 | final float range = (float) Math.abs(delta) / motionRange; 636 | duration = (int) ((range + 1) * BASE_SETTLE_DURATION); 637 | } 638 | return Math.min(duration, MAX_SETTLE_DURATION); 639 | } 640 | 641 | /** 642 | * Clamp the magnitude of value for absMin and absMax. 643 | * If the value is below the minimum, it will be clamped to zero. 644 | * If the value is above the maximum, it will be clamped to the maximum. 645 | * 646 | * @param value Value to clamp 647 | * @param absMin Absolute value of the minimum significant value to return 648 | * @param absMax Absolute value of the maximum value to return 649 | * @return The clamped value with the same sign as value 650 | */ 651 | private int clampMag(int value, int absMin, int absMax) { 652 | final int absValue = Math.abs(value); 653 | if (absValue < absMin) return 0; 654 | if (absValue > absMax) return value > 0 ? absMax : -absMax; 655 | return value; 656 | } 657 | 658 | /** 659 | * Clamp the magnitude of value for absMin and absMax. 660 | * If the value is below the minimum, it will be clamped to zero. 661 | * If the value is above the maximum, it will be clamped to the maximum. 662 | * 663 | * @param value Value to clamp 664 | * @param absMin Absolute value of the minimum significant value to return 665 | * @param absMax Absolute value of the maximum value to return 666 | * @return The clamped value with the same sign as value 667 | */ 668 | private float clampMag(float value, float absMin, float absMax) { 669 | final float absValue = Math.abs(value); 670 | if (absValue < absMin) return 0; 671 | if (absValue > absMax) return value > 0 ? absMax : -absMax; 672 | return value; 673 | } 674 | 675 | private float distanceInfluenceForSnapDuration(float f) { 676 | f -= 0.5f; // center the values about 0. 677 | f *= 0.3f * Math.PI / 2.0f; 678 | return (float) Math.sin(f); 679 | } 680 | 681 | /** 682 | * Settle the captured view based on standard free-moving fling behavior. 683 | * The caller should invoke {@link #continueSettling(boolean)} on each subsequent frame 684 | * to continue the motion until it returns false. 685 | * 686 | * @param minLeft Minimum X position for the view's left edge 687 | * @param minTop Minimum Y position for the view's top edge 688 | * @param maxLeft Maximum X position for the view's left edge 689 | * @param maxTop Maximum Y position for the view's top edge 690 | */ 691 | public void flingCapturedView(int minLeft, int minTop, int maxLeft, int maxTop) { 692 | if (!mReleaseInProgress) { 693 | throw new IllegalStateException("Cannot flingCapturedView outside of a call to " + 694 | "Callback#onViewReleased"); 695 | } 696 | 697 | mScroller.fling(mCapturedView.getLeft(), mCapturedView.getTop(), 698 | (int) VelocityTrackerCompat.getXVelocity(mVelocityTracker, mActivePointerId), 699 | (int) VelocityTrackerCompat.getYVelocity(mVelocityTracker, mActivePointerId), 700 | minLeft, maxLeft, minTop, maxTop); 701 | 702 | setDragState(STATE_SETTLING); 703 | } 704 | 705 | /** 706 | * Move the captured settling view by the appropriate amount for the current time. 707 | * If continueSettling returns true, the caller should call it again 708 | * on the next frame to continue. 709 | * 710 | * @param deferCallbacks true if state callbacks should be deferred via posted message. 711 | * Set this to true if you are calling this method from 712 | * {@link android.view.View#computeScroll()} or similar methods 713 | * invoked as part of layout or drawing. 714 | * @return true if settle is still in progress 715 | */ 716 | public boolean continueSettling(boolean deferCallbacks) { 717 | if (mDragState == STATE_SETTLING) { 718 | boolean keepGoing = mScroller.computeScrollOffset(); 719 | final int x = mScroller.getCurrX(); 720 | final int y = mScroller.getCurrY(); 721 | final int dx = x - mCapturedView.getLeft(); 722 | final int dy = y - mCapturedView.getTop(); 723 | 724 | if (dx != 0) { 725 | ViewCompat.offsetLeftAndRight(mCapturedView, dx); 726 | } 727 | if (dy != 0) { 728 | ViewCompat.offsetTopAndBottom(mCapturedView, dy); 729 | } 730 | 731 | if (dx != 0 || dy != 0) { 732 | mCallback.onViewPositionChanged(mCapturedView, x, y, dx, dy); 733 | } 734 | 735 | if (keepGoing && x == mScroller.getFinalX() && y == mScroller.getFinalY()) { 736 | // Close enough. The interpolator/scroller might think we're still moving 737 | // but the user sure doesn't. 738 | mScroller.abortAnimation(); 739 | keepGoing = false; 740 | } 741 | 742 | if (!keepGoing) { 743 | if (deferCallbacks) { 744 | mParentView.post(mSetIdleRunnable); 745 | } else { 746 | setDragState(STATE_IDLE); 747 | } 748 | } 749 | } 750 | 751 | return mDragState == STATE_SETTLING; 752 | } 753 | 754 | /** 755 | * Like all callback events this must happen on the UI thread, but release 756 | * involves some extra semantics. During a release (mReleaseInProgress) 757 | * is the only time it is valid to call {@link #settleCapturedViewAt(int, int)} 758 | * or {@link #flingCapturedView(int, int, int, int)}. 759 | */ 760 | private void dispatchViewReleased(float xvel, float yvel) { 761 | mReleaseInProgress = true; 762 | mCallback.onViewReleased(mCapturedView, xvel, yvel); 763 | mReleaseInProgress = false; 764 | 765 | if (mDragState == STATE_DRAGGING) { 766 | // onViewReleased didn't call a method that would have changed this. Go idle. 767 | setDragState(STATE_IDLE); 768 | } 769 | } 770 | 771 | private void clearMotionHistory() { 772 | if (mInitialMotionX == null) { 773 | return; 774 | } 775 | Arrays.fill(mInitialMotionX, 0); 776 | Arrays.fill(mInitialMotionY, 0); 777 | Arrays.fill(mLastMotionX, 0); 778 | Arrays.fill(mLastMotionY, 0); 779 | Arrays.fill(mInitialEdgesTouched, 0); 780 | Arrays.fill(mEdgeDragsInProgress, 0); 781 | Arrays.fill(mEdgeDragsLocked, 0); 782 | mPointersDown = 0; 783 | } 784 | 785 | private void clearMotionHistory(int pointerId) { 786 | if (mInitialMotionX == null) { 787 | return; 788 | } 789 | mInitialMotionX[pointerId] = 0; 790 | mInitialMotionY[pointerId] = 0; 791 | mLastMotionX[pointerId] = 0; 792 | mLastMotionY[pointerId] = 0; 793 | mInitialEdgesTouched[pointerId] = 0; 794 | mEdgeDragsInProgress[pointerId] = 0; 795 | mEdgeDragsLocked[pointerId] = 0; 796 | mPointersDown &= ~(1 << pointerId); 797 | } 798 | 799 | private void ensureMotionHistorySizeForId(int pointerId) { 800 | if (mInitialMotionX == null || mInitialMotionX.length <= pointerId) { 801 | float[] imx = new float[pointerId + 1]; 802 | float[] imy = new float[pointerId + 1]; 803 | float[] lmx = new float[pointerId + 1]; 804 | float[] lmy = new float[pointerId + 1]; 805 | int[] iit = new int[pointerId + 1]; 806 | int[] edip = new int[pointerId + 1]; 807 | int[] edl = new int[pointerId + 1]; 808 | 809 | if (mInitialMotionX != null) { 810 | System.arraycopy(mInitialMotionX, 0, imx, 0, mInitialMotionX.length); 811 | System.arraycopy(mInitialMotionY, 0, imy, 0, mInitialMotionY.length); 812 | System.arraycopy(mLastMotionX, 0, lmx, 0, mLastMotionX.length); 813 | System.arraycopy(mLastMotionY, 0, lmy, 0, mLastMotionY.length); 814 | System.arraycopy(mInitialEdgesTouched, 0, iit, 0, mInitialEdgesTouched.length); 815 | System.arraycopy(mEdgeDragsInProgress, 0, edip, 0, mEdgeDragsInProgress.length); 816 | System.arraycopy(mEdgeDragsLocked, 0, edl, 0, mEdgeDragsLocked.length); 817 | } 818 | 819 | mInitialMotionX = imx; 820 | mInitialMotionY = imy; 821 | mLastMotionX = lmx; 822 | mLastMotionY = lmy; 823 | mInitialEdgesTouched = iit; 824 | mEdgeDragsInProgress = edip; 825 | mEdgeDragsLocked = edl; 826 | } 827 | } 828 | 829 | private void saveInitialMotion(float x, float y, int pointerId) { 830 | ensureMotionHistorySizeForId(pointerId); 831 | mInitialMotionX[pointerId] = mLastMotionX[pointerId] = x; 832 | mInitialMotionY[pointerId] = mLastMotionY[pointerId] = y; 833 | mInitialEdgesTouched[pointerId] = getEdgesTouched((int) x, (int) y); 834 | mPointersDown |= 1 << pointerId; 835 | } 836 | 837 | private void saveLastMotion(MotionEvent ev) { 838 | final int pointerCount = MotionEventCompat.getPointerCount(ev); 839 | for (int i = 0; i < pointerCount; i++) { 840 | final int pointerId = MotionEventCompat.getPointerId(ev, i); 841 | final float x = MotionEventCompat.getX(ev, i); 842 | final float y = MotionEventCompat.getY(ev, i); 843 | mLastMotionX[pointerId] = x; 844 | mLastMotionY[pointerId] = y; 845 | } 846 | } 847 | 848 | /** 849 | * Check if the given pointer ID represents a pointer that is currently down (to the best 850 | * of the ViewDragHelper's knowledge). 851 | * 852 | *

The state used to report this information is populated by the methods 853 | * {@link #shouldInterceptTouchEvent(android.view.MotionEvent)} or 854 | * {@link #processTouchEvent(android.view.MotionEvent)}. If one of these methods has not 855 | * been called for all relevant MotionEvents to track, the information reported 856 | * by this method may be stale or incorrect.

857 | * 858 | * @param pointerId pointer ID to check; corresponds to IDs provided by MotionEvent 859 | * @return true if the pointer with the given ID is still down 860 | */ 861 | public boolean isPointerDown(int pointerId) { 862 | return (mPointersDown & 1 << pointerId) != 0; 863 | } 864 | 865 | void setDragState(int state) { 866 | mParentView.removeCallbacks(mSetIdleRunnable); 867 | if (mDragState != state) { 868 | mDragState = state; 869 | mCallback.onViewDragStateChanged(state); 870 | if (mDragState == STATE_IDLE) { 871 | mCapturedView = null; 872 | } 873 | } 874 | } 875 | 876 | /** 877 | * Attempt to capture the view with the given pointer ID. The callback will be involved. 878 | * This will put us into the "dragging" state. If we've already captured this view with 879 | * this pointer this method will immediately return true without consulting the callback. 880 | * 881 | * @param toCapture View to capture 882 | * @param pointerId Pointer to capture with 883 | * @return true if capture was successful 884 | */ 885 | boolean tryCaptureViewForDrag(View toCapture, int pointerId) { 886 | if (toCapture == mCapturedView && mActivePointerId == pointerId) { 887 | // Already done! 888 | return true; 889 | } 890 | if (toCapture != null && mCallback.tryCaptureView(toCapture, pointerId)) { 891 | mActivePointerId = pointerId; 892 | captureChildView(toCapture, pointerId); 893 | return true; 894 | } 895 | return false; 896 | } 897 | 898 | /** 899 | * Tests scrollability within child views of v given a delta of dx. 900 | * 901 | * @param v View to test for horizontal scrollability 902 | * @param checkV Whether the view v passed should itself be checked for scrollability (true), 903 | * or just its children (false). 904 | * @param dx Delta scrolled in pixels along the X axis 905 | * @param dy Delta scrolled in pixels along the Y axis 906 | * @param x X coordinate of the active touch point 907 | * @param y Y coordinate of the active touch point 908 | * @return true if child views of v can be scrolled by delta of dx. 909 | */ 910 | protected boolean canScroll(View v, boolean checkV, int dx, int dy, int x, int y) { 911 | if (v instanceof ViewGroup) { 912 | final ViewGroup group = (ViewGroup) v; 913 | final int scrollX = v.getScrollX(); 914 | final int scrollY = v.getScrollY(); 915 | final int count = group.getChildCount(); 916 | // Count backwards - let topmost views consume scroll distance first. 917 | for (int i = count - 1; i >= 0; i--) { 918 | // TODO: Add versioned support here for transformed views. 919 | // This will not work for transformed views in Honeycomb+ 920 | final View child = group.getChildAt(i); 921 | if (x + scrollX >= child.getLeft() && x + scrollX < child.getRight() && 922 | y + scrollY >= child.getTop() && y + scrollY < child.getBottom() && 923 | canScroll(child, true, dx, dy, x + scrollX - child.getLeft(), 924 | y + scrollY - child.getTop())) { 925 | return true; 926 | } 927 | } 928 | } 929 | 930 | return checkV && (ViewCompat.canScrollHorizontally(v, -dx) || 931 | ViewCompat.canScrollVertically(v, -dy)); 932 | } 933 | 934 | /** 935 | * Check if this event as provided to the parent view's onInterceptTouchEvent should 936 | * cause the parent to intercept the touch event stream. 937 | * 938 | * @param ev MotionEvent provided to onInterceptTouchEvent 939 | * @return true if the parent view should return true from onInterceptTouchEvent 940 | */ 941 | public boolean shouldInterceptTouchEvent(MotionEvent ev) { 942 | final int action = MotionEventCompat.getActionMasked(ev); 943 | final int actionIndex = MotionEventCompat.getActionIndex(ev); 944 | 945 | if (action == MotionEvent.ACTION_DOWN) { 946 | // Reset things for a new event stream, just in case we didn't get 947 | // the whole previous stream. 948 | cancel(); 949 | } 950 | 951 | if (mVelocityTracker == null) { 952 | mVelocityTracker = VelocityTracker.obtain(); 953 | } 954 | mVelocityTracker.addMovement(ev); 955 | 956 | switch (action) { 957 | case MotionEvent.ACTION_DOWN: { 958 | final float x = ev.getX(); 959 | final float y = ev.getY(); 960 | final int pointerId = MotionEventCompat.getPointerId(ev, 0); 961 | saveInitialMotion(x, y, pointerId); 962 | 963 | final View toCapture = findTopChildUnder((int) x, (int) y); 964 | 965 | // Catch a settling view if possible. 966 | if (toCapture == mCapturedView && mDragState == STATE_SETTLING) { 967 | tryCaptureViewForDrag(toCapture, pointerId); 968 | } 969 | 970 | final int edgesTouched = mInitialEdgesTouched[pointerId]; 971 | if ((edgesTouched & mTrackingEdges) != 0) { 972 | mCallback.onEdgeTouched(edgesTouched & mTrackingEdges, pointerId); 973 | } 974 | break; 975 | } 976 | 977 | case MotionEventCompat.ACTION_POINTER_DOWN: { 978 | final int pointerId = MotionEventCompat.getPointerId(ev, actionIndex); 979 | final float x = MotionEventCompat.getX(ev, actionIndex); 980 | final float y = MotionEventCompat.getY(ev, actionIndex); 981 | 982 | saveInitialMotion(x, y, pointerId); 983 | 984 | // A ViewDragHelper can only manipulate one view at a time. 985 | if (mDragState == STATE_IDLE) { 986 | final int edgesTouched = mInitialEdgesTouched[pointerId]; 987 | if ((edgesTouched & mTrackingEdges) != 0) { 988 | mCallback.onEdgeTouched(edgesTouched & mTrackingEdges, pointerId); 989 | } 990 | } else if (mDragState == STATE_SETTLING) { 991 | // Catch a settling view if possible. 992 | final View toCapture = findTopChildUnder((int) x, (int) y); 993 | if (toCapture == mCapturedView) { 994 | tryCaptureViewForDrag(toCapture, pointerId); 995 | } 996 | } 997 | break; 998 | } 999 | 1000 | case MotionEvent.ACTION_MOVE: { 1001 | if (mInitialMotionX == null || mInitialMotionY == null) break; 1002 | 1003 | // First to cross a touch slop over a draggable view wins. Also report edge drags. 1004 | final int pointerCount = MotionEventCompat.getPointerCount(ev); 1005 | for (int i = 0; i < pointerCount; i++) { 1006 | final int pointerId = MotionEventCompat.getPointerId(ev, i); 1007 | 1008 | // If pointer is invalid then skip the ACTION_MOVE. 1009 | if (!isValidPointerForActionMove(pointerId)) continue; 1010 | 1011 | final float x = MotionEventCompat.getX(ev, i); 1012 | final float y = MotionEventCompat.getY(ev, i); 1013 | final float dx = x - mInitialMotionX[pointerId]; 1014 | final float dy = y - mInitialMotionY[pointerId]; 1015 | 1016 | final View toCapture = findTopChildUnder((int) x, (int) y); 1017 | final boolean pastSlop = toCapture != null && checkTouchSlop(toCapture, dx, dy); 1018 | if (pastSlop) { 1019 | // check the callback's 1020 | // getView[Horizontal|Vertical]DragRange methods to know 1021 | // if you can move at all along an axis, then see if it 1022 | // would clamp to the same value. If you can't move at 1023 | // all in every dimension with a nonzero range, bail. 1024 | final int oldLeft = toCapture.getLeft(); 1025 | final int targetLeft = oldLeft + (int) dx; 1026 | final int newLeft = mCallback.clampViewPositionHorizontal(toCapture, 1027 | targetLeft, (int) dx); 1028 | final int oldTop = toCapture.getTop(); 1029 | final int targetTop = oldTop + (int) dy; 1030 | final int newTop = mCallback.clampViewPositionVertical(toCapture, targetTop, 1031 | (int) dy); 1032 | final int horizontalDragRange = mCallback.getViewHorizontalDragRange( 1033 | toCapture); 1034 | final int verticalDragRange = mCallback.getViewVerticalDragRange(toCapture); 1035 | if ((horizontalDragRange == 0 || horizontalDragRange > 0 1036 | && newLeft == oldLeft) && (verticalDragRange == 0 1037 | || verticalDragRange > 0 && newTop == oldTop)) { 1038 | break; 1039 | } 1040 | } 1041 | reportNewEdgeDrags(dx, dy, pointerId); 1042 | if (mDragState == STATE_DRAGGING) { 1043 | // Callback might have started an edge drag 1044 | break; 1045 | } 1046 | 1047 | if (pastSlop && tryCaptureViewForDrag(toCapture, pointerId)) { 1048 | break; 1049 | } 1050 | } 1051 | saveLastMotion(ev); 1052 | break; 1053 | } 1054 | 1055 | case MotionEventCompat.ACTION_POINTER_UP: { 1056 | final int pointerId = MotionEventCompat.getPointerId(ev, actionIndex); 1057 | clearMotionHistory(pointerId); 1058 | break; 1059 | } 1060 | 1061 | case MotionEvent.ACTION_UP: 1062 | case MotionEvent.ACTION_CANCEL: { 1063 | cancel(); 1064 | break; 1065 | } 1066 | } 1067 | 1068 | return mDragState == STATE_DRAGGING; 1069 | } 1070 | 1071 | /** 1072 | * Process a touch event received by the parent view. This method will dispatch callback events 1073 | * as needed before returning. The parent view's onTouchEvent implementation should call this. 1074 | * 1075 | * @param ev The touch event received by the parent view 1076 | */ 1077 | public void processTouchEvent(MotionEvent ev) { 1078 | final int action = MotionEventCompat.getActionMasked(ev); 1079 | final int actionIndex = MotionEventCompat.getActionIndex(ev); 1080 | 1081 | if (action == MotionEvent.ACTION_DOWN) { 1082 | // Reset things for a new event stream, just in case we didn't get 1083 | // the whole previous stream. 1084 | cancel(); 1085 | } 1086 | 1087 | if (mVelocityTracker == null) { 1088 | mVelocityTracker = VelocityTracker.obtain(); 1089 | } 1090 | mVelocityTracker.addMovement(ev); 1091 | 1092 | switch (action) { 1093 | case MotionEvent.ACTION_DOWN: { 1094 | final float x = ev.getX(); 1095 | final float y = ev.getY(); 1096 | final int pointerId = MotionEventCompat.getPointerId(ev, 0); 1097 | final View toCapture = findTopChildUnder((int) x, (int) y); 1098 | 1099 | saveInitialMotion(x, y, pointerId); 1100 | 1101 | // Since the parent is already directly processing this touch event, 1102 | // there is no reason to delay for a slop before dragging. 1103 | // Start immediately if possible. 1104 | tryCaptureViewForDrag(toCapture, pointerId); 1105 | 1106 | final int edgesTouched = mInitialEdgesTouched[pointerId]; 1107 | if ((edgesTouched & mTrackingEdges) != 0) { 1108 | mCallback.onEdgeTouched(edgesTouched & mTrackingEdges, pointerId); 1109 | } 1110 | break; 1111 | } 1112 | 1113 | case MotionEventCompat.ACTION_POINTER_DOWN: { 1114 | final int pointerId = MotionEventCompat.getPointerId(ev, actionIndex); 1115 | final float x = MotionEventCompat.getX(ev, actionIndex); 1116 | final float y = MotionEventCompat.getY(ev, actionIndex); 1117 | 1118 | saveInitialMotion(x, y, pointerId); 1119 | 1120 | // A ViewDragHelper can only manipulate one view at a time. 1121 | if (mDragState == STATE_IDLE) { 1122 | // If we're idle we can do anything! Treat it like a normal down event. 1123 | 1124 | final View toCapture = findTopChildUnder((int) x, (int) y); 1125 | tryCaptureViewForDrag(toCapture, pointerId); 1126 | 1127 | final int edgesTouched = mInitialEdgesTouched[pointerId]; 1128 | if ((edgesTouched & mTrackingEdges) != 0) { 1129 | mCallback.onEdgeTouched(edgesTouched & mTrackingEdges, pointerId); 1130 | } 1131 | } else if (isCapturedViewUnder((int) x, (int) y)) { 1132 | // We're still tracking a captured view. If the same view is under this 1133 | // point, we'll swap to controlling it with this pointer instead. 1134 | // (This will still work if we're "catching" a settling view.) 1135 | 1136 | tryCaptureViewForDrag(mCapturedView, pointerId); 1137 | } 1138 | break; 1139 | } 1140 | 1141 | case MotionEvent.ACTION_MOVE: { 1142 | if (mDragState == STATE_DRAGGING) { 1143 | // If pointer is invalid then skip the ACTION_MOVE. 1144 | if (!isValidPointerForActionMove(mActivePointerId)) break; 1145 | 1146 | final int index = MotionEventCompat.findPointerIndex(ev, mActivePointerId); 1147 | final float x = MotionEventCompat.getX(ev, index); 1148 | final float y = MotionEventCompat.getY(ev, index); 1149 | final int idx = (int) (x - mLastMotionX[mActivePointerId]); 1150 | final int idy = (int) (y - mLastMotionY[mActivePointerId]); 1151 | 1152 | dragTo(mCapturedView.getLeft() + idx, mCapturedView.getTop() + idy, idx, idy); 1153 | 1154 | saveLastMotion(ev); 1155 | } else { 1156 | // Check to see if any pointer is now over a draggable view. 1157 | final int pointerCount = MotionEventCompat.getPointerCount(ev); 1158 | for (int i = 0; i < pointerCount; i++) { 1159 | final int pointerId = MotionEventCompat.getPointerId(ev, i); 1160 | 1161 | // If pointer is invalid then skip the ACTION_MOVE. 1162 | if (!isValidPointerForActionMove(pointerId)) continue; 1163 | 1164 | final float x = MotionEventCompat.getX(ev, i); 1165 | final float y = MotionEventCompat.getY(ev, i); 1166 | final float dx = x - mInitialMotionX[pointerId]; 1167 | final float dy = y - mInitialMotionY[pointerId]; 1168 | 1169 | reportNewEdgeDrags(dx, dy, pointerId); 1170 | if (mDragState == STATE_DRAGGING) { 1171 | // Callback might have started an edge drag. 1172 | break; 1173 | } 1174 | 1175 | final View toCapture = findTopChildUnder((int) x, (int) y); 1176 | if (checkTouchSlop(toCapture, dx, dy) && 1177 | tryCaptureViewForDrag(toCapture, pointerId)) { 1178 | break; 1179 | } 1180 | } 1181 | saveLastMotion(ev); 1182 | } 1183 | break; 1184 | } 1185 | 1186 | case MotionEventCompat.ACTION_POINTER_UP: { 1187 | final int pointerId = MotionEventCompat.getPointerId(ev, actionIndex); 1188 | if (mDragState == STATE_DRAGGING && pointerId == mActivePointerId) { 1189 | // Try to find another pointer that's still holding on to the captured view. 1190 | int newActivePointer = INVALID_POINTER; 1191 | final int pointerCount = MotionEventCompat.getPointerCount(ev); 1192 | for (int i = 0; i < pointerCount; i++) { 1193 | final int id = MotionEventCompat.getPointerId(ev, i); 1194 | if (id == mActivePointerId) { 1195 | // This one's going away, skip. 1196 | continue; 1197 | } 1198 | 1199 | final float x = MotionEventCompat.getX(ev, i); 1200 | final float y = MotionEventCompat.getY(ev, i); 1201 | if (findTopChildUnder((int) x, (int) y) == mCapturedView && 1202 | tryCaptureViewForDrag(mCapturedView, id)) { 1203 | newActivePointer = mActivePointerId; 1204 | break; 1205 | } 1206 | } 1207 | 1208 | if (newActivePointer == INVALID_POINTER) { 1209 | // We didn't find another pointer still touching the view, release it. 1210 | releaseViewForPointerUp(); 1211 | } 1212 | } 1213 | clearMotionHistory(pointerId); 1214 | break; 1215 | } 1216 | 1217 | case MotionEvent.ACTION_UP: { 1218 | if (mDragState == STATE_DRAGGING) { 1219 | releaseViewForPointerUp(); 1220 | } 1221 | cancel(); 1222 | break; 1223 | } 1224 | 1225 | case MotionEvent.ACTION_CANCEL: { 1226 | if (mDragState == STATE_DRAGGING) { 1227 | dispatchViewReleased(0, 0); 1228 | } 1229 | cancel(); 1230 | break; 1231 | } 1232 | } 1233 | } 1234 | 1235 | private void reportNewEdgeDrags(float dx, float dy, int pointerId) { 1236 | int dragsStarted = 0; 1237 | if (checkNewEdgeDrag(dx, dy, pointerId, EDGE_LEFT)) { 1238 | dragsStarted |= EDGE_LEFT; 1239 | } 1240 | if (checkNewEdgeDrag(dy, dx, pointerId, EDGE_TOP)) { 1241 | dragsStarted |= EDGE_TOP; 1242 | } 1243 | if (checkNewEdgeDrag(dx, dy, pointerId, EDGE_RIGHT)) { 1244 | dragsStarted |= EDGE_RIGHT; 1245 | } 1246 | if (checkNewEdgeDrag(dy, dx, pointerId, EDGE_BOTTOM)) { 1247 | dragsStarted |= EDGE_BOTTOM; 1248 | } 1249 | 1250 | if (dragsStarted != 0) { 1251 | mEdgeDragsInProgress[pointerId] |= dragsStarted; 1252 | mCallback.onEdgeDragStarted(dragsStarted, pointerId); 1253 | } 1254 | } 1255 | 1256 | private boolean checkNewEdgeDrag(float delta, float odelta, int pointerId, int edge) { 1257 | final float absDelta = Math.abs(delta); 1258 | final float absODelta = Math.abs(odelta); 1259 | 1260 | if ((mInitialEdgesTouched[pointerId] & edge) != edge || (mTrackingEdges & edge) == 0 || 1261 | (mEdgeDragsLocked[pointerId] & edge) == edge || 1262 | (mEdgeDragsInProgress[pointerId] & edge) == edge || 1263 | (absDelta <= mTouchSlop && absODelta <= mTouchSlop)) { 1264 | return false; 1265 | } 1266 | if (absDelta < absODelta * 0.5f && mCallback.onEdgeLock(edge)) { 1267 | mEdgeDragsLocked[pointerId] |= edge; 1268 | return false; 1269 | } 1270 | return (mEdgeDragsInProgress[pointerId] & edge) == 0 && absDelta > mTouchSlop; 1271 | } 1272 | 1273 | /** 1274 | * Check if we've crossed a reasonable touch slop for the given child view. 1275 | * If the child cannot be dragged along the horizontal or vertical axis, motion 1276 | * along that axis will not count toward the slop check. 1277 | * 1278 | * @param child Child to check 1279 | * @param dx Motion since initial position along X axis 1280 | * @param dy Motion since initial position along Y axis 1281 | * @return true if the touch slop has been crossed 1282 | */ 1283 | private boolean checkTouchSlop(View child, float dx, float dy) { 1284 | if (child == null) { 1285 | return false; 1286 | } 1287 | final boolean checkHorizontal = mCallback.getViewHorizontalDragRange(child) > 0; 1288 | final boolean checkVertical = mCallback.getViewVerticalDragRange(child) > 0; 1289 | 1290 | if (checkHorizontal && checkVertical) { 1291 | return dx * dx + dy * dy > mTouchSlop * mTouchSlop; 1292 | } else if (checkHorizontal) { 1293 | return Math.abs(dx) > mTouchSlop; 1294 | } else if (checkVertical) { 1295 | return Math.abs(dy) > mTouchSlop; 1296 | } 1297 | return false; 1298 | } 1299 | 1300 | /** 1301 | * Check if any pointer tracked in the current gesture has crossed 1302 | * the required slop threshold. 1303 | * 1304 | *

This depends on internal state populated by 1305 | * {@link #shouldInterceptTouchEvent(android.view.MotionEvent)} or 1306 | * {@link #processTouchEvent(android.view.MotionEvent)}. You should only rely on 1307 | * the results of this method after all currently available touch data 1308 | * has been provided to one of these two methods.

1309 | * 1310 | * @param directions Combination of direction flags, see {@link #DIRECTION_HORIZONTAL}, 1311 | * {@link #DIRECTION_VERTICAL}, {@link #DIRECTION_ALL} 1312 | * @return true if the slop threshold has been crossed, false otherwise 1313 | */ 1314 | public boolean checkTouchSlop(int directions) { 1315 | final int count = mInitialMotionX.length; 1316 | for (int i = 0; i < count; i++) { 1317 | if (checkTouchSlop(directions, i)) { 1318 | return true; 1319 | } 1320 | } 1321 | return false; 1322 | } 1323 | 1324 | /** 1325 | * Check if the specified pointer tracked in the current gesture has crossed 1326 | * the required slop threshold. 1327 | * 1328 | *

This depends on internal state populated by 1329 | * {@link #shouldInterceptTouchEvent(android.view.MotionEvent)} or 1330 | * {@link #processTouchEvent(android.view.MotionEvent)}. You should only rely on 1331 | * the results of this method after all currently available touch data 1332 | * has been provided to one of these two methods.

1333 | * 1334 | * @param directions Combination of direction flags, see {@link #DIRECTION_HORIZONTAL}, 1335 | * {@link #DIRECTION_VERTICAL}, {@link #DIRECTION_ALL} 1336 | * @param pointerId ID of the pointer to slop check as specified by MotionEvent 1337 | * @return true if the slop threshold has been crossed, false otherwise 1338 | */ 1339 | public boolean checkTouchSlop(int directions, int pointerId) { 1340 | if (!isPointerDown(pointerId)) { 1341 | return false; 1342 | } 1343 | 1344 | final boolean checkHorizontal = (directions & DIRECTION_HORIZONTAL) == DIRECTION_HORIZONTAL; 1345 | final boolean checkVertical = (directions & DIRECTION_VERTICAL) == DIRECTION_VERTICAL; 1346 | 1347 | final float dx = mLastMotionX[pointerId] - mInitialMotionX[pointerId]; 1348 | final float dy = mLastMotionY[pointerId] - mInitialMotionY[pointerId]; 1349 | 1350 | if (checkHorizontal && checkVertical) { 1351 | return dx * dx + dy * dy > mTouchSlop * mTouchSlop; 1352 | } else if (checkHorizontal) { 1353 | return Math.abs(dx) > mTouchSlop; 1354 | } else if (checkVertical) { 1355 | return Math.abs(dy) > mTouchSlop; 1356 | } 1357 | return false; 1358 | } 1359 | 1360 | /** 1361 | * Check if any of the edges specified were initially touched in the currently active gesture. 1362 | * If there is no currently active gesture this method will return false. 1363 | * 1364 | * @param edges Edges to check for an initial edge touch. See {@link #EDGE_LEFT}, 1365 | * {@link #EDGE_TOP}, {@link #EDGE_RIGHT}, {@link #EDGE_BOTTOM} and 1366 | * {@link #EDGE_ALL} 1367 | * @return true if any of the edges specified were initially touched in the current gesture 1368 | */ 1369 | public boolean isEdgeTouched(int edges) { 1370 | final int count = mInitialEdgesTouched.length; 1371 | for (int i = 0; i < count; i++) { 1372 | if (isEdgeTouched(edges, i)) { 1373 | return true; 1374 | } 1375 | } 1376 | return false; 1377 | } 1378 | 1379 | /** 1380 | * Check if any of the edges specified were initially touched by the pointer with 1381 | * the specified ID. If there is no currently active gesture or if there is no pointer with 1382 | * the given ID currently down this method will return false. 1383 | * 1384 | * @param edges Edges to check for an initial edge touch. See {@link #EDGE_LEFT}, 1385 | * {@link #EDGE_TOP}, {@link #EDGE_RIGHT}, {@link #EDGE_BOTTOM} and 1386 | * {@link #EDGE_ALL} 1387 | * @return true if any of the edges specified were initially touched in the current gesture 1388 | */ 1389 | public boolean isEdgeTouched(int edges, int pointerId) { 1390 | return isPointerDown(pointerId) && (mInitialEdgesTouched[pointerId] & edges) != 0; 1391 | } 1392 | 1393 | private void releaseViewForPointerUp() { 1394 | mVelocityTracker.computeCurrentVelocity(1000, mMaxVelocity); 1395 | final float xvel = clampMag( 1396 | VelocityTrackerCompat.getXVelocity(mVelocityTracker, mActivePointerId), 1397 | mMinVelocity, mMaxVelocity); 1398 | final float yvel = clampMag( 1399 | VelocityTrackerCompat.getYVelocity(mVelocityTracker, mActivePointerId), 1400 | mMinVelocity, mMaxVelocity); 1401 | dispatchViewReleased(xvel, yvel); 1402 | } 1403 | 1404 | private void dragTo(int left, int top, int dx, int dy) { 1405 | int clampedX = left; 1406 | int clampedY = top; 1407 | final int oldLeft = mCapturedView.getLeft(); 1408 | final int oldTop = mCapturedView.getTop(); 1409 | if (dx != 0) { 1410 | clampedX = mCallback.clampViewPositionHorizontal(mCapturedView, left, dx); 1411 | ViewCompat.offsetLeftAndRight(mCapturedView, clampedX - oldLeft); 1412 | } 1413 | if (dy != 0) { 1414 | clampedY = mCallback.clampViewPositionVertical(mCapturedView, top, dy); 1415 | ViewCompat.offsetTopAndBottom(mCapturedView, clampedY - oldTop); 1416 | } 1417 | 1418 | if (dx != 0 || dy != 0) { 1419 | final int clampedDx = clampedX - oldLeft; 1420 | final int clampedDy = clampedY - oldTop; 1421 | mCallback.onViewPositionChanged(mCapturedView, clampedX, clampedY, 1422 | clampedDx, clampedDy); 1423 | } 1424 | } 1425 | 1426 | /** 1427 | * Determine if the currently captured view is under the given point in the 1428 | * parent view's coordinate system. If there is no captured view this method 1429 | * will return false. 1430 | * 1431 | * @param x X position to test in the parent's coordinate system 1432 | * @param y Y position to test in the parent's coordinate system 1433 | * @return true if the captured view is under the given point, false otherwise 1434 | */ 1435 | public boolean isCapturedViewUnder(int x, int y) { 1436 | return isViewUnder(mCapturedView, x, y); 1437 | } 1438 | 1439 | /** 1440 | * Determine if the supplied view is under the given point in the 1441 | * parent view's coordinate system. 1442 | * 1443 | * @param view Child view of the parent to hit test 1444 | * @param x X position to test in the parent's coordinate system 1445 | * @param y Y position to test in the parent's coordinate system 1446 | * @return true if the supplied view is under the given point, false otherwise 1447 | */ 1448 | public boolean isViewUnder(View view, int x, int y) { 1449 | if (view == null) { 1450 | return false; 1451 | } 1452 | return x >= view.getLeft() && 1453 | x < view.getRight() && 1454 | y >= view.getTop() && 1455 | y < view.getBottom(); 1456 | } 1457 | 1458 | /** 1459 | * Find the topmost child under the given point within the parent view's coordinate system. 1460 | * The child order is determined using {@link Callback#getOrderedChildIndex(int)}. 1461 | * 1462 | * @param x X position to test in the parent's coordinate system 1463 | * @param y Y position to test in the parent's coordinate system 1464 | * @return The topmost child view under (x, y) or null if none found. 1465 | */ 1466 | public View findTopChildUnder(int x, int y) { 1467 | final int childCount = mParentView.getChildCount(); 1468 | for (int i = childCount - 1; i >= 0; i--) { 1469 | final View child = mParentView.getChildAt(mCallback.getOrderedChildIndex(i)); 1470 | if (x >= child.getLeft() && x < child.getRight() && 1471 | y >= child.getTop() && y < child.getBottom()) { 1472 | return child; 1473 | } 1474 | } 1475 | return null; 1476 | } 1477 | 1478 | private int getEdgesTouched(int x, int y) { 1479 | int result = 0; 1480 | 1481 | if (x < mParentView.getLeft() + mEdgeSize) result |= EDGE_LEFT; 1482 | if (y < mParentView.getTop() + mEdgeSize) result |= EDGE_TOP; 1483 | if (x > mParentView.getRight() - mEdgeSize) result |= EDGE_RIGHT; 1484 | if (y > mParentView.getBottom() - mEdgeSize) result |= EDGE_BOTTOM; 1485 | 1486 | return result; 1487 | } 1488 | 1489 | private boolean isValidPointerForActionMove(int pointerId) { 1490 | if (!isPointerDown(pointerId)) { 1491 | Log.e(TAG, "Ignoring pointerId=" + pointerId + " because ACTION_DOWN was not received " 1492 | + "for this pointer before ACTION_MOVE. It likely happened because " 1493 | + " ViewDragHelper did not receive all the events in the event stream."); 1494 | return false; 1495 | } 1496 | return true; 1497 | } 1498 | } 1499 | --------------------------------------------------------------------------------