├── app ├── .gitignore ├── src │ └── main │ │ ├── res │ │ ├── values │ │ │ ├── strings.xml │ │ │ ├── colors.xml │ │ │ ├── dimens.xml │ │ │ ├── swipe_adapter_view.xml │ │ │ └── styles.xml │ │ ├── mipmap-hdpi │ │ │ └── ic_launcher.png │ │ ├── mipmap-mdpi │ │ │ └── ic_launcher.png │ │ ├── mipmap-xhdpi │ │ │ └── ic_launcher.png │ │ ├── mipmap-xxhdpi │ │ │ └── ic_launcher.png │ │ ├── mipmap-xxxhdpi │ │ │ └── ic_launcher.png │ │ ├── drawable-xxhdpi │ │ │ ├── default_card.png │ │ │ ├── home01_bg_card.9.png │ │ │ ├── home01_icon_edu.png │ │ │ ├── home01_btn_collect.png │ │ │ ├── home01_icon_location.png │ │ │ └── home01_icon_work_year.png │ │ ├── values-w820dp │ │ │ └── dimens.xml │ │ └── layout │ │ │ ├── activity_main.xml │ │ │ └── card_new_item.xml │ │ ├── AndroidManifest.xml │ │ └── java │ │ └── me │ │ └── payge │ │ ├── main │ │ └── MainActivity.java │ │ └── swipeadapterview │ │ ├── SwipeAdapterView.java │ │ └── ViewDragHelper.java ├── proguard-rules.pro └── build.gradle ├── settings.gradle ├── animImage.gif ├── Screenshot.png ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── .gitignore ├── gradle.properties ├── README.md ├── gradlew.bat ├── gradlew └── LICENSE /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app' 2 | -------------------------------------------------------------------------------- /animImage.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiepeijie/SwipeAdapterView/HEAD/animImage.gif -------------------------------------------------------------------------------- /Screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiepeijie/SwipeAdapterView/HEAD/Screenshot.png -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | SwipeAdapterView 3 | 4 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiepeijie/SwipeAdapterView/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /.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/xiepeijie/SwipeAdapterView/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiepeijie/SwipeAdapterView/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiepeijie/SwipeAdapterView/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiepeijie/SwipeAdapterView/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiepeijie/SwipeAdapterView/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-xxhdpi/default_card.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiepeijie/SwipeAdapterView/HEAD/app/src/main/res/drawable-xxhdpi/default_card.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-xxhdpi/home01_bg_card.9.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiepeijie/SwipeAdapterView/HEAD/app/src/main/res/drawable-xxhdpi/home01_bg_card.9.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-xxhdpi/home01_icon_edu.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiepeijie/SwipeAdapterView/HEAD/app/src/main/res/drawable-xxhdpi/home01_icon_edu.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-xxhdpi/home01_btn_collect.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiepeijie/SwipeAdapterView/HEAD/app/src/main/res/drawable-xxhdpi/home01_btn_collect.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-xxhdpi/home01_icon_location.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiepeijie/SwipeAdapterView/HEAD/app/src/main/res/drawable-xxhdpi/home01_icon_location.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-xxhdpi/home01_icon_work_year.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiepeijie/SwipeAdapterView/HEAD/app/src/main/res/drawable-xxhdpi/home01_icon_work_year.png -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #666666 4 | #666666 5 | #FF4081 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16dp 4 | 16dp 5 | 6 | -------------------------------------------------------------------------------- /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-4.4-all.zip 7 | -------------------------------------------------------------------------------- /app/src/main/res/values-w820dp/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 64dp 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/swipe_adapter_view.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 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 E:\IDE\Android\sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 15 | 16 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 27 5 | 6 | defaultConfig { 7 | applicationId "me.payge.swipeadapterview" 8 | minSdkVersion 14 9 | targetSdkVersion 27 10 | versionCode 1 11 | versionName "1.0" 12 | } 13 | buildTypes { 14 | release { 15 | minifyEnabled false 16 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 17 | } 18 | } 19 | } 20 | 21 | dependencies { 22 | implementation fileTree(dir: 'libs', include: ['*.jar']) 23 | implementation 'com.android.support:appcompat-v7:27.1.1' 24 | implementation 'com.github.bumptech.glide:glide:3.7.0' 25 | } 26 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m 13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | # org.gradle.parallel=true -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SwipeAdapterView 2 | 3 | SwipeAdapterView is a widget that can slide by ViewDragHelper, it is like Tinder APP, swipe left means dislike, swipe right means like. 4 | It is optimize and implement based on the [SwipeCardView](https://github.com/xiepeijie/SwipeCardView), slide by ViewDragHelper, solves the problem of slide and click on events in the SwipeCardView conflict, also increased the child view reuse cached, enhance widget performance. 5 | You can also see my another project — [SwipeCardView](https://github.com/xiepeijie/SwipeCardView). 6 | 7 | ## Screenshot 8 | 9 | ![img](https://github.com/xiepeijie/SwipeAdapterView/blob/master/animImage.gif) 10 | 11 | ## About me 12 | 13 | [@萧雾宇](http://weibo.com/payge) 14 | 15 | ## License 16 | ``` 17 | Copyright 2016 xiepeijie 18 | 19 | Licensed under the Apache License, Version 2.0 (the "License"); 20 | you may not use this file except in compliance with the License. 21 | You may obtain a copy of the License at 22 | 23 | http://www.apache.org/licenses/LICENSE-2.0 24 | 25 | Unless required by applicable law or agreed to in writing, software 26 | distributed under the License is distributed on an "AS IS" BASIS, 27 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 28 | See the License for the specific language governing permissions and 29 | limitations under the License. 30 | ``` 31 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /app/src/main/res/layout/card_new_item.xml: -------------------------------------------------------------------------------- 1 | 2 | 11 | 12 | 18 | 19 | 26 | 27 | 35 | 36 | 49 | 59 | 69 | 70 | 82 | 83 | 84 | 85 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /app/src/main/java/me/payge/main/MainActivity.java: -------------------------------------------------------------------------------- 1 | package me.payge.main; 2 | 3 | import android.os.AsyncTask; 4 | import android.os.Bundle; 5 | import android.support.v7.app.AppCompatActivity; 6 | import android.util.DisplayMetrics; 7 | import android.util.Log; 8 | import android.view.LayoutInflater; 9 | import android.view.View; 10 | import android.view.ViewGroup; 11 | import android.widget.BaseAdapter; 12 | import android.widget.CheckedTextView; 13 | import android.widget.ImageView; 14 | import android.widget.TextView; 15 | 16 | import com.bumptech.glide.Glide; 17 | 18 | import java.util.ArrayList; 19 | import java.util.Collection; 20 | import java.util.List; 21 | import java.util.Random; 22 | 23 | import me.payge.swipeadapterview.R; 24 | import me.payge.swipeadapterview.SwipeAdapterView; 25 | 26 | public class MainActivity extends AppCompatActivity implements SwipeAdapterView.onFlingListener, 27 | SwipeAdapterView.OnItemClickListener { 28 | 29 | String [] headerIcons = {"http://www.5djiaren.com/uploads/2015-04/17-115301_29.jpg", 30 | "http://img1.dzwww.com:8080/tupian_pl/20160106/32/4152697013403556460.jpg", 31 | "http://c.hiphotos.baidu.com/zhidao/pic/item/72f082025aafa40f191362cfad64034f79f019ce.jpg", 32 | "http://img.article.pchome.net/new/w600/00/35/15/66/pic_lib/wm/122532981493137o3iegiyx.jpg", 33 | "http://img0.imgtn.bdimg.com/it/u=3382799710,1639843170&fm=21&gp=0.jpg", 34 | "http://i2.sinaimg.cn/travel/2014/0918/U7398P704DT20140918143217.jpg", 35 | "http://photo.l99.com/bigger/21/1415193165405_4sg3ds.jpg", 36 | "http://img.pconline.com.cn/images/upload/upc/tx/photoblog/1305/15/c2/20949108_20949108_1368599174341.jpg", 37 | "http://pic29.nipic.com/20130501/12558275_114724775130_2.jpg", 38 | "http://photo.l99.com/bigger/20/1415193157174_j2fa5b.jpg"}; 39 | 40 | String [] names = {"张三","李四","王五","小明","小红","小花"}; 41 | 42 | String [] citys = {"北京", "上海", "广州", "深圳"}; 43 | 44 | String [] edus = {"大专", "本科", "硕士", "博士"}; 45 | 46 | String [] years = {"1年", "2年", "3年", "4年", "5年"}; 47 | 48 | Random ran = new Random(); 49 | 50 | private int cardWidth; 51 | private int cardHeight; 52 | 53 | private SwipeAdapterView swipeView; 54 | private InnerAdapter adapter; 55 | 56 | 57 | @Override 58 | protected void onCreate(Bundle savedInstanceState) { 59 | super.onCreate(savedInstanceState); 60 | setContentView(R.layout.activity_main); 61 | 62 | initView(); 63 | loadData(); 64 | } 65 | 66 | private void initView() { 67 | DisplayMetrics dm = getResources().getDisplayMetrics(); 68 | float density = dm.density; 69 | cardWidth = (int) (dm.widthPixels - (2 * 18 * density)); 70 | cardHeight = (int) (dm.heightPixels - (338 * density)); 71 | 72 | 73 | swipeView = (SwipeAdapterView) findViewById(R.id.swipe_view); 74 | // swipeView.setIsNeedSwipe(false); 75 | swipeView.setFlingListener(this); 76 | swipeView.setOnItemClickListener(this); 77 | 78 | adapter = new InnerAdapter(); 79 | swipeView.setAdapter(adapter); 80 | } 81 | 82 | 83 | @Override 84 | public void onItemClicked(View v, Object dataObject) { 85 | Log.i("tag", "click top view"); 86 | } 87 | 88 | @Override 89 | public void removeFirstObjectInAdapter(View topView) { 90 | adapter.remove(0); 91 | } 92 | 93 | @Override 94 | public void onLeftCardExit(Object dataObject) { 95 | Log.i("tag", "swipe left"); 96 | } 97 | 98 | @Override 99 | public void onRightCardExit(Object dataObject) { 100 | Log.i("tag", "swipe right"); 101 | } 102 | 103 | @Override 104 | public void onAdapterAboutToEmpty(int itemsInAdapter) { 105 | if (itemsInAdapter == 3) { 106 | loadData(); 107 | } 108 | } 109 | 110 | @Override 111 | public void onScroll(float progress, float scrollXProgress) { 112 | } 113 | 114 | private void loadData() { 115 | new AsyncTask>() { 116 | @Override 117 | protected List doInBackground(Void... params) { 118 | ArrayList list = new ArrayList<>(10); 119 | Talent talent; 120 | for (int i = 0; i < 10; i++) { 121 | talent = new Talent(); 122 | talent.headerIcon = headerIcons[i]; 123 | talent.nickname = names[ran.nextInt(names.length-1)]; 124 | talent.cityName = citys[ran.nextInt(citys.length-1)]; 125 | talent.educationName = edus[ran.nextInt(edus.length-1)]; 126 | talent.workYearName = years[ran.nextInt(years.length-1)]; 127 | list.add(talent); 128 | } 129 | return list; 130 | } 131 | 132 | @Override 133 | protected void onPostExecute(List list) { 134 | super.onPostExecute(list); 135 | adapter.addAll(list); 136 | } 137 | }.execute(); 138 | } 139 | 140 | 141 | private class InnerAdapter extends BaseAdapter implements View.OnClickListener { 142 | 143 | ArrayList objs; 144 | 145 | public InnerAdapter() { 146 | objs = new ArrayList<>(); 147 | } 148 | 149 | public void addAll(Collection collection) { 150 | if (isEmpty()) { 151 | objs.addAll(collection); 152 | notifyDataSetChanged(); 153 | } else { 154 | objs.addAll(collection); 155 | } 156 | } 157 | 158 | public void clear() { 159 | objs.clear(); 160 | notifyDataSetChanged(); 161 | } 162 | 163 | public boolean isEmpty() { 164 | return objs.isEmpty(); 165 | } 166 | 167 | public void remove(int index) { 168 | if (index > -1 && index < objs.size()) { 169 | objs.remove(index); 170 | notifyDataSetChanged(); 171 | } 172 | } 173 | 174 | 175 | @Override 176 | public int getCount() { 177 | return objs.size(); 178 | } 179 | 180 | @Override 181 | public Talent getItem(int position) { 182 | if(objs==null ||objs.size()==0) return null; 183 | return objs.get(position); 184 | } 185 | 186 | @Override 187 | public long getItemId(int position) { 188 | return position; 189 | } 190 | 191 | @Override 192 | public View getView(int position, View convertView, ViewGroup parent) { 193 | ViewHolder holder; 194 | Talent talent = getItem(position); 195 | if (convertView == null) { 196 | convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_new_item, parent, false); 197 | holder = new ViewHolder(); 198 | convertView.setTag(holder); 199 | convertView.getLayoutParams().width = cardWidth; 200 | holder.portraitView = (ImageView) convertView.findViewById(R.id.portrait); 201 | //holder.portraitView.getLayoutParams().width = cardWidth; 202 | holder.portraitView.getLayoutParams().height = cardHeight; 203 | holder.nameView = (TextView) convertView.findViewById(R.id.name); 204 | //parentView.getLayoutParams().width = cardWidth; 205 | //holder.jobView = (TextView) convertView.findViewById(R.id.job); 206 | //holder.companyView = (TextView) convertView.findViewById(R.id.company); 207 | holder.cityView = (TextView) convertView.findViewById(R.id.city); 208 | holder.eduView = (TextView) convertView.findViewById(R.id.education); 209 | holder.workView = (TextView) convertView.findViewById(R.id.work_year); 210 | holder.collectView = (CheckedTextView) convertView.findViewById(R.id.favorite); 211 | holder.collectView.setTag("关注"); 212 | holder.collectView.setOnClickListener(this); 213 | } else { 214 | //Log.e("tag", "recycler convertView"); 215 | holder = (ViewHolder) convertView.getTag(); 216 | } 217 | 218 | Glide.with(parent.getContext()).load(talent.headerIcon) 219 | .centerCrop().placeholder(R.drawable.default_card) 220 | .into(holder.portraitView); 221 | holder.nameView.setText(String.format("%s", talent.nickname)); 222 | 223 | final CharSequence no = "暂无"; 224 | 225 | holder.cityView.setHint(no); 226 | holder.cityView.setText(talent.cityName); 227 | holder.cityView.setCompoundDrawablesWithIntrinsicBounds(0,R.drawable.home01_icon_location,0,0); 228 | 229 | holder.eduView.setHint(no); 230 | holder.eduView.setText(talent.educationName); 231 | holder.eduView.setCompoundDrawablesWithIntrinsicBounds(0,R.drawable.home01_icon_edu,0,0); 232 | 233 | holder.workView.setHint(no); 234 | holder.workView.setText(talent.workYearName); 235 | holder.workView.setCompoundDrawablesWithIntrinsicBounds(0,R.drawable.home01_icon_work_year,0,0); 236 | 237 | 238 | return convertView; 239 | } 240 | 241 | @Override 242 | public void onClick(View v) { 243 | Log.i("tag", "onClick: " + v.getTag()); 244 | } 245 | } 246 | 247 | private static class ViewHolder { 248 | ImageView portraitView; 249 | TextView nameView; 250 | TextView cityView; 251 | TextView eduView; 252 | TextView workView; 253 | CheckedTextView collectView; 254 | } 255 | 256 | public static class Talent { 257 | public String headerIcon; 258 | public String nickname; 259 | public String cityName; 260 | public String educationName; 261 | public String workYearName; 262 | } 263 | 264 | } 265 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /app/src/main/java/me/payge/swipeadapterview/SwipeAdapterView.java: -------------------------------------------------------------------------------- 1 | package me.payge.swipeadapterview; 2 | 3 | import android.animation.Animator; 4 | import android.animation.AnimatorListenerAdapter; 5 | import android.animation.ValueAnimator; 6 | import android.content.Context; 7 | import android.content.res.TypedArray; 8 | import android.database.DataSetObserver; 9 | import android.os.Build; 10 | import android.support.v4.view.ViewCompat; 11 | import android.support.v4.widget.ViewDragHelper; 12 | import android.util.AttributeSet; 13 | import android.util.Log; 14 | import android.view.Gravity; 15 | import android.view.MotionEvent; 16 | import android.view.View; 17 | import android.view.ViewPropertyAnimator; 18 | import android.widget.Adapter; 19 | import android.widget.AdapterView; 20 | import android.widget.FrameLayout; 21 | 22 | 23 | import java.util.ArrayList; 24 | 25 | /** 26 | * @author payge 27 | * 通过ViewDragHelper实现拖拽滑动 28 | */ 29 | public class SwipeAdapterView extends AdapterView { 30 | 31 | private ArrayList cache = new ArrayList<>(); 32 | 33 | //缩放层叠效果 34 | private int yOffsetStep; // view叠加垂直偏移量的步长 35 | private static final float SCALE_STEP = 0.08f; // view叠加缩放的步长 36 | //缩放层叠效果 37 | 38 | private int MAX_VISIBLE = 4; // 值建议最小为4 39 | private int MIN_ADAPTER_STACK = 6; 40 | private float ROTATION_DEGREES = 2f; 41 | private int LAST_VIEW_IN_STACK = 0; 42 | 43 | private Adapter mAdapter; 44 | private onFlingListener mFlingListener; 45 | private AdapterDataSetObserver mDataSetObserver; 46 | private boolean mInLayout = false; 47 | private View mActiveCard = null; 48 | private OnItemClickListener mOnItemClickListener; 49 | 50 | // 是否支持拖拽滑动 51 | public boolean isNeedSwipe = true; 52 | // 是否支持左右滑动飞出边界动画 53 | public boolean isNeedSwipeAnim = true; 54 | 55 | private int initTop; 56 | private int initLeft; 57 | 58 | private boolean isSwipeAnimRunning; 59 | private int cLeft, cTop; 60 | 61 | private ViewDragHelper viewDragHelper; 62 | //private GestureDetectorCompat detector; 63 | 64 | private int widthMeasureSpec; 65 | private int heightMeasureSpec; 66 | 67 | private float x, y; 68 | 69 | public SwipeAdapterView(Context context) { 70 | this(context, null); 71 | } 72 | 73 | public SwipeAdapterView(Context context, AttributeSet attrs) { 74 | this(context, attrs, 0); 75 | } 76 | 77 | public SwipeAdapterView(Context context, AttributeSet attrs, int defStyle) { 78 | super(context, attrs, defStyle); 79 | 80 | TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SwipeAdapterView, defStyle, 0); 81 | MAX_VISIBLE = a.getInt(R.styleable.SwipeAdapterView_max_visible, MAX_VISIBLE); 82 | MIN_ADAPTER_STACK = a.getInt(R.styleable.SwipeAdapterView_min_adapter_stack, MIN_ADAPTER_STACK); 83 | ROTATION_DEGREES = a.getFloat(R.styleable.SwipeAdapterView_rotation_degrees, ROTATION_DEGREES); 84 | yOffsetStep = a.getDimensionPixelOffset(R.styleable.SwipeAdapterView_y_offset_step, 0); 85 | a.recycle(); 86 | 87 | viewDragHelper = ViewDragHelper.create(this, 4f, callback); 88 | } 89 | 90 | public void setIsNeedSwipe(boolean isNeedSwipe) { 91 | this.isNeedSwipe = isNeedSwipe; 92 | } 93 | 94 | public void setIsNeedSwipeAnim(boolean isNeedSwipeAnim) { 95 | this.isNeedSwipeAnim = isNeedSwipeAnim; 96 | } 97 | 98 | @Override 99 | protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 100 | super.onMeasure(widthMeasureSpec, heightMeasureSpec); 101 | this.widthMeasureSpec = widthMeasureSpec; 102 | this.heightMeasureSpec = heightMeasureSpec; 103 | } 104 | 105 | @Override 106 | public View getSelectedView() { 107 | return mActiveCard; 108 | } 109 | 110 | @Override 111 | public void setSelection(int position) { 112 | throw new UnsupportedOperationException("Not supported"); 113 | } 114 | 115 | @Override 116 | public void computeScroll() { 117 | super.computeScroll(); 118 | if (viewDragHelper.continueSettling(false)) { 119 | ViewCompat.postInvalidateOnAnimation(this); 120 | } else { 121 | if (isSwipeAnimRunning) { 122 | isSwipeAnimRunning = false; 123 | //Log.i("tag", "computeScroll"); 124 | //adjustChildrenOfUnderTopView(1f); 125 | if (mFlingListener != null) { 126 | if (mActiveCard.getLeft() > 0) { 127 | mFlingListener.onRightCardExit(mAdapter.getItem(0)); 128 | } else { 129 | mFlingListener.onLeftCardExit(mAdapter.getItem(0)); 130 | } 131 | mFlingListener.removeFirstObjectInAdapter(mActiveCard); 132 | } 133 | mActiveCard = null; 134 | } 135 | cLeft = 0; 136 | cTop = 0; 137 | } 138 | } 139 | 140 | @Override 141 | public boolean onInterceptTouchEvent(MotionEvent ev) { 142 | boolean b = viewDragHelper.shouldInterceptTouchEvent(ev); 143 | if (ev.getActionMasked() == MotionEvent.ACTION_DOWN) { 144 | viewDragHelper.processTouchEvent(ev); 145 | } 146 | float dx = 0, dy = 0; 147 | if (ev.getActionMasked() == MotionEvent.ACTION_DOWN) { 148 | x = ev.getX(); 149 | y = ev.getY(); 150 | } else if (ev.getActionMasked() == MotionEvent.ACTION_MOVE) { 151 | dx = Math.abs(ev.getX() - x); 152 | dy = Math.abs(ev.getY() - y); 153 | x = ev.getX(); 154 | y = ev.getY(); 155 | } else if (ev.getActionMasked() == MotionEvent.ACTION_UP) { 156 | x = 0; 157 | y = 0; 158 | } 159 | boolean scroll = dx > 4 || dy > 4; 160 | //Log.i("tag", String.format("onScroll: %s %s %s", scroll, dx, dy)); 161 | return b && isNeedSwipe && scroll; 162 | } 163 | 164 | @Override 165 | public boolean onTouchEvent(MotionEvent event) { 166 | viewDragHelper.processTouchEvent(event); 167 | return isNeedSwipe; 168 | } 169 | 170 | @Override 171 | public void requestLayout() { 172 | if (!mInLayout) { 173 | super.requestLayout(); 174 | } 175 | } 176 | 177 | @Override 178 | protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 179 | super.onLayout(changed, left, top, right, bottom); 180 | // if we don't have an adapter, we don't need to do anything 181 | if (mAdapter == null) { 182 | return; 183 | } 184 | 185 | mInLayout = true; 186 | final int adapterCount = mAdapter.getCount(); 187 | if (adapterCount == 0) { 188 | // removeAllViewsInLayout(); 189 | removeViewToCache(0); 190 | } else { 191 | View topCard = getChildAt(LAST_VIEW_IN_STACK); 192 | if(mActiveCard != null && topCard != null && topCard == mActiveCard) { 193 | // removeViewsInLayout(0, LAST_VIEW_IN_STACK); 194 | removeViewToCache(1); 195 | layoutChildren(1, adapterCount); 196 | }else{ 197 | // Reset the UI and set top view listener 198 | // removeAllViewsInLayout(); 199 | removeViewToCache(0); 200 | layoutChildren(0, adapterCount); 201 | setTopView(); 202 | } 203 | } 204 | mInLayout = false; 205 | 206 | if (initTop == 0 && initLeft == 0 && mActiveCard != null) { 207 | initTop = mActiveCard.getTop(); 208 | initLeft = mActiveCard.getLeft(); 209 | } 210 | 211 | if(adapterCount < MIN_ADAPTER_STACK) { 212 | if(mFlingListener != null){ 213 | mFlingListener.onAdapterAboutToEmpty(adapterCount); 214 | } 215 | } 216 | } 217 | 218 | private void removeViewToCache(int saveCount) { 219 | View child; 220 | for (int i = 0; i < getChildCount() - saveCount; ) { 221 | child = getChildAt(i); 222 | removeViewInLayout(child); 223 | cache.add(child); 224 | } 225 | } 226 | 227 | private void layoutChildren(int startingIndex, int adapterCount){ 228 | while (startingIndex < Math.min(adapterCount, MAX_VISIBLE) ) { 229 | View cacheView = null; 230 | if (cache.size() > 0) { 231 | cacheView = cache.get(0); 232 | cache.remove(cacheView); 233 | } 234 | View newUnderChild = mAdapter.getView(startingIndex, cacheView, this); 235 | if (newUnderChild.getVisibility() != GONE) { 236 | makeAndAddView(newUnderChild, startingIndex); 237 | LAST_VIEW_IN_STACK = startingIndex; 238 | } 239 | startingIndex++; 240 | } 241 | } 242 | 243 | private void makeAndAddView(View child, int index) { 244 | child.setAlpha(1F); 245 | child.setTranslationX(0); 246 | FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) child.getLayoutParams(); 247 | addViewInLayout(child, 0, lp, true); 248 | 249 | final boolean needToMeasure = child.isLayoutRequested(); 250 | if (needToMeasure) { 251 | int childWidthSpec = getChildMeasureSpec(widthMeasureSpec, 252 | getPaddingLeft() + getPaddingRight() + lp.leftMargin + lp.rightMargin, 253 | lp.width); 254 | int childHeightSpec = getChildMeasureSpec(heightMeasureSpec, 255 | getPaddingTop() + getPaddingBottom() + lp.topMargin + lp.bottomMargin, 256 | lp.height); 257 | child.measure(childWidthSpec, childHeightSpec); 258 | } else { 259 | cleanupLayoutState(child); 260 | } 261 | 262 | int w = child.getMeasuredWidth(); 263 | int h = child.getMeasuredHeight(); 264 | 265 | int gravity = lp.gravity; 266 | if (gravity == -1) { 267 | gravity = Gravity.TOP | Gravity.START; 268 | } 269 | 270 | int layoutDirection = 0; 271 | if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) 272 | layoutDirection = getLayoutDirection(); 273 | final int absoluteGravity = Gravity.getAbsoluteGravity(gravity, layoutDirection); 274 | final int verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK; 275 | 276 | int childLeft; 277 | int childTop; 278 | switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) { 279 | case Gravity.CENTER_HORIZONTAL: 280 | childLeft = (getWidth() + getPaddingLeft() - getPaddingRight() - w) / 2 + 281 | lp.leftMargin - lp.rightMargin; 282 | break; 283 | case Gravity.END: 284 | childLeft = getWidth() + getPaddingRight() - w - lp.rightMargin; 285 | break; 286 | case Gravity.START: 287 | default: 288 | childLeft = getPaddingLeft() + lp.leftMargin; 289 | break; 290 | } 291 | switch (verticalGravity) { 292 | case Gravity.CENTER_VERTICAL: 293 | childTop = (getHeight() + getPaddingTop() - getPaddingBottom() - h) / 2 + 294 | lp.topMargin - lp.bottomMargin; 295 | break; 296 | case Gravity.BOTTOM: 297 | childTop = getHeight() - getPaddingBottom() - h - lp.bottomMargin; 298 | break; 299 | case Gravity.TOP: 300 | default: 301 | childTop = getPaddingTop() + lp.topMargin; 302 | break; 303 | } 304 | child.layout(childLeft, childTop, childLeft + w, childTop + h); 305 | // 缩放层叠效果 306 | adjustChildView(child, index); 307 | } 308 | 309 | private void adjustChildView(View child, int index) { 310 | if (index > -1 && index < MAX_VISIBLE) { 311 | int multiple; 312 | if (index > 2) multiple = 2; 313 | else multiple = index; 314 | child.offsetTopAndBottom(yOffsetStep * multiple); 315 | child.setScaleX(1 - SCALE_STEP * multiple); 316 | child.setScaleY(1 - SCALE_STEP * multiple); 317 | } 318 | } 319 | 320 | private void adjustChildrenOfUnderTopView(float scrollRate) { 321 | int count = getChildCount(); 322 | if (count > 1) { 323 | int i; 324 | int multiple; 325 | if (count == 2) { 326 | i = LAST_VIEW_IN_STACK - 1; 327 | multiple = 1; 328 | } else { 329 | i = LAST_VIEW_IN_STACK - 2; 330 | multiple = 2; 331 | } 332 | float rate = Math.abs(scrollRate); 333 | for (; i < LAST_VIEW_IN_STACK; i++, multiple--) { 334 | View underTopView = getChildAt(i); 335 | int offset = (int) (yOffsetStep * (multiple - rate)); 336 | underTopView.offsetTopAndBottom(offset - underTopView.getTop() + initTop); 337 | underTopView.setScaleX(1 - SCALE_STEP * multiple + SCALE_STEP * rate); 338 | underTopView.setScaleY(1 - SCALE_STEP * multiple + SCALE_STEP * rate); 339 | } 340 | } 341 | } 342 | 343 | /** 344 | * Set the top view and add the fling listener 345 | */ 346 | private void setTopView() { 347 | if(getChildCount() > 0){ 348 | mActiveCard = getChildAt(LAST_VIEW_IN_STACK); 349 | if(mActiveCard != null) { 350 | mActiveCard.setOnClickListener(new OnClickListener() { 351 | @Override 352 | public void onClick(View v) { 353 | //Log.i("tag", "onClick: top view"); 354 | if (mOnItemClickListener != null) 355 | mOnItemClickListener.onItemClicked(v, mAdapter.getItem(0)); 356 | } 357 | }); 358 | } 359 | } 360 | } 361 | 362 | public void setMaxVisible(int MAX_VISIBLE){ 363 | this.MAX_VISIBLE = MAX_VISIBLE; 364 | } 365 | 366 | public void setMinStackInAdapter(int MIN_ADAPTER_STACK){ 367 | this.MIN_ADAPTER_STACK = MIN_ADAPTER_STACK; 368 | } 369 | 370 | @Override 371 | public Adapter getAdapter() { 372 | return mAdapter; 373 | } 374 | 375 | 376 | @Override 377 | public void setAdapter(Adapter adapter) { 378 | if (mAdapter != null && mDataSetObserver != null) { 379 | mAdapter.unregisterDataSetObserver(mDataSetObserver); 380 | mDataSetObserver = null; 381 | } 382 | 383 | mAdapter = adapter; 384 | 385 | if (mAdapter != null && mDataSetObserver == null) { 386 | mDataSetObserver = new AdapterDataSetObserver(); 387 | mAdapter.registerDataSetObserver(mDataSetObserver); 388 | } 389 | } 390 | 391 | public void setFlingListener(onFlingListener onFlingListener) { 392 | this.mFlingListener = onFlingListener; 393 | } 394 | 395 | public void setOnItemClickListener(OnItemClickListener onItemClickListener){ 396 | this.mOnItemClickListener = onItemClickListener; 397 | } 398 | 399 | 400 | @Override 401 | public LayoutParams generateLayoutParams(AttributeSet attrs) { 402 | return new FrameLayout.LayoutParams(getContext(), attrs); 403 | } 404 | 405 | 406 | private class AdapterDataSetObserver extends DataSetObserver { 407 | @Override 408 | public void onChanged() { 409 | requestLayout(); 410 | } 411 | 412 | @Override 413 | public void onInvalidated() { 414 | requestLayout(); 415 | } 416 | 417 | } 418 | 419 | 420 | public interface OnItemClickListener { 421 | void onItemClicked(View v, Object dataObject); 422 | } 423 | 424 | public interface onFlingListener { 425 | void removeFirstObjectInAdapter(View topView); 426 | void onLeftCardExit(Object dataObject); 427 | void onRightCardExit(Object dataObject); 428 | void onAdapterAboutToEmpty(int itemsInAdapter); 429 | void onScroll(float progress, float scrollXProgress); 430 | } 431 | 432 | public static class FlingListenerAdapter implements onFlingListener { 433 | 434 | @Override 435 | public void removeFirstObjectInAdapter(View topView) { 436 | } 437 | 438 | @Override 439 | public void onLeftCardExit(Object dataObject) { 440 | } 441 | 442 | @Override 443 | public void onRightCardExit(Object dataObject) { 444 | } 445 | 446 | @Override 447 | public void onAdapterAboutToEmpty(int itemsInAdapter) { 448 | } 449 | 450 | @Override 451 | public void onScroll(float progress, float scrollXProgress) { 452 | } 453 | } 454 | 455 | private ViewDragHelper.Callback callback = new ViewDragHelper.Callback() { 456 | 457 | // int disX, disY; 458 | 459 | @Override 460 | public boolean tryCaptureView(View child, int pointerId) { 461 | cLeft = child.getLeft(); 462 | cTop = child.getTop(); 463 | return child == mActiveCard; 464 | } 465 | 466 | @Override 467 | public int clampViewPositionHorizontal(View child, int left, int dx) { 468 | return left; 469 | } 470 | 471 | @Override 472 | public int clampViewPositionVertical(View child, int top, int dy) { 473 | return top; 474 | } 475 | 476 | @Override 477 | public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) { 478 | int offsetX = left - cLeft; 479 | int offsetY = top - cTop; 480 | float progress = 1f * (Math.abs(offsetX) + Math.abs(offsetY)) / 400; 481 | float scrollX = 1f * Math.abs(offsetX) / 400; 482 | progress = Math.min(progress, 1f); 483 | scrollX = Math.min(scrollX, 1f); 484 | //Log.i("tag", "onViewPositionChanged: " + progress); 485 | adjustChildrenOfUnderTopView(progress); 486 | if (mFlingListener != null) 487 | mFlingListener.onScroll(progress, scrollX); 488 | } 489 | 490 | @Override 491 | public void onViewReleased(View releasedChild, float xvel, float yvel) { 492 | int disX = releasedChild.getLeft() - cLeft; 493 | int disY = releasedChild.getTop() - cTop; 494 | int endTop = releasedChild.getTop(); 495 | int offsetTop = getHeight() / 6; 496 | if (disY > offsetTop) { 497 | endTop += 2 * offsetTop; 498 | } else if (disY < -offsetTop){ 499 | endTop -= 2 * offsetTop; 500 | } 501 | if (isNeedSwipeAnim) { 502 | if (disX > getWidth() / 4) { 503 | isSwipeAnimRunning = true; 504 | viewDragHelper.smoothSlideViewTo(releasedChild, getWidth() + 200, endTop); 505 | invalidate(); 506 | } else if (disX < -(getWidth() / 4)) { 507 | isSwipeAnimRunning = true; 508 | viewDragHelper.smoothSlideViewTo(releasedChild, -getWidth(), endTop); 509 | invalidate(); 510 | } else { 511 | viewDragHelper.smoothSlideViewTo(releasedChild, initLeft, initTop); 512 | invalidate(); 513 | } 514 | } else { 515 | viewDragHelper.smoothSlideViewTo(releasedChild, initLeft, initTop); 516 | invalidate(); 517 | } 518 | } 519 | }; 520 | 521 | public void swipeLeft() { 522 | swipeTopView(1, 280); 523 | } 524 | 525 | public void swipeRight() { 526 | swipeTopView(0, 280); 527 | } 528 | 529 | private void swipeTopView(int direction, int duration) { 530 | final View activeView = mActiveCard; 531 | if (activeView == null) return; 532 | AnimatorListenerAdapter listenerAdapter = new AnimatorListenerAdapter() { 533 | @Override 534 | public void onAnimationEnd(Animator animation) { 535 | super.onAnimationEnd(animation); 536 | if (mFlingListener != null) { 537 | mFlingListener.removeFirstObjectInAdapter(activeView); 538 | } 539 | mActiveCard = null; 540 | } 541 | }; 542 | final int maxTranslationX = (int) Math.min(activeView.getWidth() / 4, 200 * getResources().getDisplayMetrics().density); 543 | ValueAnimator.AnimatorUpdateListener updateListener = new ValueAnimator.AnimatorUpdateListener() { 544 | @Override 545 | public void onAnimationUpdate(ValueAnimator animation) { 546 | float offsetX = Math.abs(activeView.getTranslationX()); 547 | //Log.i("tag", "onAnimationUpdate: " + offsetX); 548 | float progress = offsetX / maxTranslationX; 549 | adjustChildrenOfUnderTopView(progress); 550 | } 551 | }; 552 | ViewPropertyAnimator animator = activeView.animate(); 553 | //right 554 | if (direction == 0) { 555 | animator.alpha(0) 556 | .translationX(maxTranslationX) 557 | .setDuration(duration) 558 | .setListener(listenerAdapter); 559 | 560 | //left 561 | } else if (direction == 1) { 562 | animator.alpha(0) 563 | .translationX(-maxTranslationX) 564 | .setDuration(duration) 565 | .setListener(listenerAdapter); 566 | } 567 | if (Build.VERSION.SDK_INT >= 19) { 568 | animator.setUpdateListener(updateListener); 569 | } 570 | animator.start(); 571 | } 572 | 573 | } 574 | -------------------------------------------------------------------------------- /app/src/main/java/me/payge/swipeadapterview/ViewDragHelper.java: -------------------------------------------------------------------------------- 1 | package me.payge.swipeadapterview; 2 | 3 | 4 | import java.util.Arrays; 5 | 6 | import android.content.Context; 7 | import android.support.v4.view.MotionEventCompat; 8 | import android.support.v4.view.VelocityTrackerCompat; 9 | import android.support.v4.view.ViewCompat; 10 | import android.support.v4.widget.ScrollerCompat; 11 | import android.view.MotionEvent; 12 | import android.view.VelocityTracker; 13 | import android.view.View; 14 | import android.view.ViewConfiguration; 15 | import android.view.ViewGroup; 16 | import android.view.animation.Interpolator; 17 | 18 | /** 19 | * ViewDragHelper is a utility class for writing custom ViewGroups. It offers a number 20 | * of useful operations and state tracking for allowing a user to drag and reposition 21 | * views within their parent ViewGroup. 22 | */ 23 | public class ViewDragHelper { 24 | // private static final String TAG = "ViewDragHelper"; 25 | 26 | /** 27 | * A null/invalid pointer ID. 28 | */ 29 | public static final int INVALID_POINTER = -1; 30 | 31 | /** 32 | * A view is not currently being dragged or animating as a result of a fling/snap. 33 | */ 34 | public static final int STATE_IDLE = 0; 35 | 36 | /** 37 | * A view is currently being dragged. The position is currently changing as a result 38 | * of user input or simulated user input. 39 | */ 40 | public static final int STATE_DRAGGING = 1; 41 | 42 | /** 43 | * A view is currently settling into place as a result of a fling or 44 | * predefined non-interactive motion. 45 | */ 46 | public static final int STATE_SETTLING = 2; 47 | 48 | /** 49 | * Edge flag indicating that the left edge should be affected. 50 | */ 51 | public static final int EDGE_LEFT = 1 << 0; 52 | 53 | /** 54 | * Edge flag indicating that the right edge should be affected. 55 | */ 56 | public static final int EDGE_RIGHT = 1 << 1; 57 | 58 | /** 59 | * Edge flag indicating that the top edge should be affected. 60 | */ 61 | public static final int EDGE_TOP = 1 << 2; 62 | 63 | /** 64 | * Edge flag indicating that the bottom edge should be affected. 65 | */ 66 | public static final int EDGE_BOTTOM = 1 << 3; 67 | 68 | /** 69 | * Edge flag set indicating all edges should be affected. 70 | */ 71 | public static final int EDGE_ALL = EDGE_LEFT | EDGE_TOP | EDGE_RIGHT | EDGE_BOTTOM; 72 | 73 | /** 74 | * Indicates that a check should occur along the horizontal axis 75 | */ 76 | public static final int DIRECTION_HORIZONTAL = 1 << 0; 77 | 78 | /** 79 | * Indicates that a check should occur along the vertical axis 80 | */ 81 | public static final int DIRECTION_VERTICAL = 1 << 1; 82 | 83 | /** 84 | * Indicates that a check should occur along all axes 85 | */ 86 | public static final int DIRECTION_ALL = DIRECTION_HORIZONTAL | DIRECTION_VERTICAL; 87 | 88 | private static final int EDGE_SIZE = 20; // dp 89 | 90 | private static final int BASE_SETTLE_DURATION = 256; // ms 91 | private static final int MAX_SETTLE_DURATION = 600; // ms 92 | 93 | // Current drag state; idle, dragging or settling 94 | private int mDragState; 95 | 96 | // Distance to travel before a drag may begin 97 | private int mTouchSlop; 98 | 99 | // Last known position/pointer tracking 100 | private int mActivePointerId = INVALID_POINTER; 101 | private float[] mInitialMotionX; 102 | private float[] mInitialMotionY; 103 | private float[] mLastMotionX; 104 | private float[] mLastMotionY; 105 | private int[] mInitialEdgesTouched; 106 | private int[] mEdgeDragsInProgress; 107 | private int[] mEdgeDragsLocked; 108 | private int mPointersDown; 109 | 110 | private VelocityTracker mVelocityTracker; 111 | private float mMaxVelocity; 112 | private float mMinVelocity; 113 | 114 | private int mEdgeSize; 115 | private int mTrackingEdges; 116 | 117 | private ScrollerCompat mScroller; 118 | 119 | private final Callback mCallback; 120 | 121 | private View mCapturedView; 122 | private boolean mReleaseInProgress; 123 | 124 | private final ViewGroup mParentView; 125 | 126 | /** 127 | * A Callback is used as a communication channel with the ViewDragHelper back to the 128 | * parent view using it. on*methods are invoked on siginficant events and several 129 | * accessor methods are expected to provide the ViewDragHelper with more information 130 | * about the state of the parent view upon request. The callback also makes decisions 131 | * governing the range and draggability of child views. 132 | */ 133 | public static abstract class Callback { 134 | /** 135 | * Called when the drag state changes. See the STATE_* constants 136 | * for more information. 137 | * 138 | * @param state The new drag state 139 | * 140 | * @see #STATE_IDLE 141 | * @see #STATE_DRAGGING 142 | * @see #STATE_SETTLING 143 | */ 144 | public void onViewDragStateChanged(int state) {} 145 | 146 | /** 147 | * Called when the captured view's position changes as the result of a drag or settle. 148 | * 149 | * @param changedView View whose position changed 150 | * @param left New X coordinate of the left edge of the view 151 | * @param top New Y coordinate of the top edge of the view 152 | * @param dx Change in X position from the last call 153 | * @param dy Change in Y position from the last call 154 | */ 155 | public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {} 156 | 157 | /** 158 | * Called when a child view is captured for dragging or settling. The ID of the pointer 159 | * currently dragging the captured view is supplied. If activePointerId is 160 | * identified as {@link #INVALID_POINTER} the capture is programmatic instead of 161 | * pointer-initiated. 162 | * 163 | * @param capturedChild Child view that was captured 164 | * @param activePointerId Pointer id tracking the child capture 165 | */ 166 | public void onViewCaptured(View capturedChild, int activePointerId) {} 167 | 168 | /** 169 | * Called when the child view is no longer being actively dragged. 170 | * The fling velocity is also supplied, if relevant. The velocity values may 171 | * be clamped to system minimums or maximums. 172 | * 173 | *

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

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

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

267 | * 268 | *

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

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

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

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

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

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

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

1264 | * 1265 | * @param directions Combination of direction flags, see {@link #DIRECTION_HORIZONTAL}, 1266 | * {@link #DIRECTION_VERTICAL}, {@link #DIRECTION_ALL} 1267 | * @return true if the slop threshold has been crossed, false otherwise 1268 | */ 1269 | public boolean checkTouchSlop(int directions) { 1270 | final int count = mInitialMotionX.length; 1271 | for (int i = 0; i < count; i++) { 1272 | if (checkTouchSlop(directions, i)) { 1273 | return true; 1274 | } 1275 | } 1276 | return false; 1277 | } 1278 | 1279 | /** 1280 | * Check if the specified pointer tracked in the current gesture has crossed 1281 | * the required slop threshold. 1282 | * 1283 | *

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

1288 | * 1289 | * @param directions Combination of direction flags, see {@link #DIRECTION_HORIZONTAL}, 1290 | * {@link #DIRECTION_VERTICAL}, {@link #DIRECTION_ALL} 1291 | * @param pointerId ID of the pointer to slop check as specified by MotionEvent 1292 | * @return true if the slop threshold has been crossed, false otherwise 1293 | */ 1294 | public boolean checkTouchSlop(int directions, int pointerId) { 1295 | if (!isPointerDown(pointerId)) { 1296 | return false; 1297 | } 1298 | 1299 | final boolean checkHorizontal = (directions & DIRECTION_HORIZONTAL) == DIRECTION_HORIZONTAL; 1300 | final boolean checkVertical = (directions & DIRECTION_VERTICAL) == DIRECTION_VERTICAL; 1301 | 1302 | final float dx = mLastMotionX[pointerId] - mInitialMotionX[pointerId]; 1303 | final float dy = mLastMotionY[pointerId] - mInitialMotionY[pointerId]; 1304 | 1305 | if (checkHorizontal && checkVertical) { 1306 | return dx * dx + dy * dy > mTouchSlop * mTouchSlop; 1307 | } else if (checkHorizontal) { 1308 | return Math.abs(dx) > mTouchSlop; 1309 | } else if (checkVertical) { 1310 | return Math.abs(dy) > mTouchSlop; 1311 | } 1312 | return false; 1313 | } 1314 | 1315 | /** 1316 | * Check if any of the edges specified were initially touched in the currently active gesture. 1317 | * If there is no currently active gesture this method will return false. 1318 | * 1319 | * @param edges Edges to check for an initial edge touch. See {@link #EDGE_LEFT}, 1320 | * {@link #EDGE_TOP}, {@link #EDGE_RIGHT}, {@link #EDGE_BOTTOM} and 1321 | * {@link #EDGE_ALL} 1322 | * @return true if any of the edges specified were initially touched in the current gesture 1323 | */ 1324 | public boolean isEdgeTouched(int edges) { 1325 | final int count = mInitialEdgesTouched.length; 1326 | for (int i = 0; i < count; i++) { 1327 | if (isEdgeTouched(edges, i)) { 1328 | return true; 1329 | } 1330 | } 1331 | return false; 1332 | } 1333 | 1334 | /** 1335 | * Check if any of the edges specified were initially touched by the pointer with 1336 | * the specified ID. If there is no currently active gesture or if there is no pointer with 1337 | * the given ID currently down this method will return false. 1338 | * 1339 | * @param edges Edges to check for an initial edge touch. See {@link #EDGE_LEFT}, 1340 | * {@link #EDGE_TOP}, {@link #EDGE_RIGHT}, {@link #EDGE_BOTTOM} and 1341 | * {@link #EDGE_ALL} 1342 | * @return true if any of the edges specified were initially touched in the current gesture 1343 | */ 1344 | public boolean isEdgeTouched(int edges, int pointerId) { 1345 | return isPointerDown(pointerId) && (mInitialEdgesTouched[pointerId] & edges) != 0; 1346 | } 1347 | 1348 | private void releaseViewForPointerUp() { 1349 | mVelocityTracker.computeCurrentVelocity(1000, mMaxVelocity); 1350 | final float xvel = clampMag( 1351 | VelocityTrackerCompat.getXVelocity(mVelocityTracker, mActivePointerId), 1352 | mMinVelocity, mMaxVelocity); 1353 | final float yvel = clampMag( 1354 | VelocityTrackerCompat.getYVelocity(mVelocityTracker, mActivePointerId), 1355 | mMinVelocity, mMaxVelocity); 1356 | dispatchViewReleased(xvel, yvel); 1357 | } 1358 | 1359 | private void dragTo(int left, int top, int dx, int dy) { 1360 | int clampedX = left; 1361 | int clampedY = top; 1362 | final int oldLeft = mCapturedView.getLeft(); 1363 | final int oldTop = mCapturedView.getTop(); 1364 | if (dx != 0) { 1365 | clampedX = mCallback.clampViewPositionHorizontal(mCapturedView, left, dx); 1366 | mCapturedView.offsetLeftAndRight(clampedX - oldLeft); 1367 | } 1368 | if (dy != 0) { 1369 | clampedY = mCallback.clampViewPositionVertical(mCapturedView, top, dy); 1370 | mCapturedView.offsetTopAndBottom(clampedY - oldTop); 1371 | } 1372 | 1373 | if (dx != 0 || dy != 0) { 1374 | final int clampedDx = clampedX - oldLeft; 1375 | final int clampedDy = clampedY - oldTop; 1376 | mCallback.onViewPositionChanged(mCapturedView, clampedX, clampedY, 1377 | clampedDx, clampedDy); 1378 | } 1379 | } 1380 | 1381 | /** 1382 | * Determine if the currently captured view is under the given point in the 1383 | * parent view's coordinate system. If there is no captured view this method 1384 | * will return false. 1385 | * 1386 | * @param x X position to test in the parent's coordinate system 1387 | * @param y Y position to test in the parent's coordinate system 1388 | * @return true if the captured view is under the given point, false otherwise 1389 | */ 1390 | public boolean isCapturedViewUnder(int x, int y) { 1391 | return isViewUnder(mCapturedView, x, y); 1392 | } 1393 | 1394 | /** 1395 | * Determine if the supplied view is under the given point in the 1396 | * parent view's coordinate system. 1397 | * 1398 | * @param view Child view of the parent to hit test 1399 | * @param x X position to test in the parent's coordinate system 1400 | * @param y Y position to test in the parent's coordinate system 1401 | * @return true if the supplied view is under the given point, false otherwise 1402 | */ 1403 | public boolean isViewUnder(View view, int x, int y) { 1404 | if (view == null) { 1405 | return false; 1406 | } 1407 | return x >= view.getLeft() && 1408 | x < view.getRight() && 1409 | y >= view.getTop() && 1410 | y < view.getBottom(); 1411 | } 1412 | 1413 | /** 1414 | * Find the topmost child under the given point within the parent view's coordinate system. 1415 | * The child order is determined using {@link Callback#getOrderedChildIndex(int)}. 1416 | * 1417 | * @param x X position to test in the parent's coordinate system 1418 | * @param y Y position to test in the parent's coordinate system 1419 | * @return The topmost child view under (x, y) or null if none found. 1420 | */ 1421 | public View findTopChildUnder(int x, int y) { 1422 | final int childCount = mParentView.getChildCount(); 1423 | for (int i = childCount - 1; i >= 0; i--) { 1424 | final View child = mParentView.getChildAt(mCallback.getOrderedChildIndex(i)); 1425 | if (x >= child.getLeft() && x < child.getRight() && 1426 | y >= child.getTop() && y < child.getBottom()) { 1427 | return child; 1428 | } 1429 | } 1430 | return null; 1431 | } 1432 | 1433 | private int getEdgesTouched(int x, int y) { 1434 | int result = 0; 1435 | 1436 | if (x < mParentView.getLeft() + mEdgeSize) result |= EDGE_LEFT; 1437 | if (y < mParentView.getTop() + mEdgeSize) result |= EDGE_TOP; 1438 | if (x > mParentView.getRight() - mEdgeSize) result |= EDGE_RIGHT; 1439 | if (y > mParentView.getBottom() - mEdgeSize) result |= EDGE_BOTTOM; 1440 | 1441 | return result; 1442 | } 1443 | } --------------------------------------------------------------------------------