├── .idea ├── .name ├── copyright │ └── profiles_settings.xml ├── vcs.xml ├── modules.xml ├── gradle.xml ├── compiler.xml └── misc.xml ├── app ├── .gitignore ├── src │ └── main │ │ ├── res │ │ ├── drawable-hdpi │ │ │ ├── loading_04.png │ │ │ ├── ic_launcher.png │ │ │ ├── pull_to_refresh_flip.png │ │ │ └── pull_to_refresh_rotate.png │ │ ├── drawable-mdpi │ │ │ └── ic_launcher.png │ │ ├── drawable-xhdpi │ │ │ ├── ic_launcher.png │ │ │ ├── pull_to_refresh_flip.png │ │ │ └── pull_to_refresh_rotate.png │ │ ├── drawable-xxhdpi │ │ │ └── ic_launcher.png │ │ ├── values │ │ │ ├── styles.xml │ │ │ └── strings.xml │ │ ├── drawable │ │ │ └── common_loading_progress_bar.xml │ │ └── layout │ │ │ ├── activity_main.xml │ │ │ ├── image_list_item.xml │ │ │ ├── pull_to_refresh_footer_view.xml │ │ │ ├── common_loading_data_view.xml │ │ │ └── pull_to_refresh_header_view.xml │ │ ├── java │ │ └── neal │ │ │ ├── activity │ │ │ └── TestActivity.java │ │ │ ├── adapterview │ │ │ ├── core │ │ │ │ ├── FooterLayout.java │ │ │ │ ├── header │ │ │ │ │ ├── FlipLoadingLayout.java │ │ │ │ │ └── LoadingLayout.java │ │ │ │ ├── PullToRefreshLayout.java │ │ │ │ └── ViewDragHelper.java │ │ │ ├── GridView.java │ │ │ └── ListView.java │ │ │ └── utils │ │ │ └── VersionUtil.java │ │ └── AndroidManifest.xml ├── build.gradle ├── proguard-rules.pro └── app.iml ├── settings.gradle ├── 001.png ├── 002.png ├── 003.png ├── 004.png ├── 005.png ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── .gitignore ├── gradle.properties ├── pulltorefresh.iml ├── README.md ├── gradlew.bat └── gradlew /.idea/.name: -------------------------------------------------------------------------------- 1 | pulltorefresh -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app' 2 | -------------------------------------------------------------------------------- /001.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sddyljsx/pulltorefresh/HEAD/001.png -------------------------------------------------------------------------------- /002.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sddyljsx/pulltorefresh/HEAD/002.png -------------------------------------------------------------------------------- /003.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sddyljsx/pulltorefresh/HEAD/003.png -------------------------------------------------------------------------------- /004.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sddyljsx/pulltorefresh/HEAD/004.png -------------------------------------------------------------------------------- /005.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sddyljsx/pulltorefresh/HEAD/005.png -------------------------------------------------------------------------------- /.idea/copyright/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sddyljsx/pulltorefresh/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | /local.properties 3 | /.idea/workspace.xml 4 | /.idea/libraries 5 | .DS_Store 6 | /build 7 | /captures 8 | -------------------------------------------------------------------------------- /app/src/main/res/drawable-hdpi/loading_04.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sddyljsx/pulltorefresh/HEAD/app/src/main/res/drawable-hdpi/loading_04.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sddyljsx/pulltorefresh/HEAD/app/src/main/res/drawable-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sddyljsx/pulltorefresh/HEAD/app/src/main/res/drawable-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sddyljsx/pulltorefresh/HEAD/app/src/main/res/drawable-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/java/neal/activity/TestActivity.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sddyljsx/pulltorefresh/HEAD/app/src/main/java/neal/activity/TestActivity.java -------------------------------------------------------------------------------- /app/src/main/res/drawable-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sddyljsx/pulltorefresh/HEAD/app/src/main/res/drawable-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-hdpi/pull_to_refresh_flip.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sddyljsx/pulltorefresh/HEAD/app/src/main/res/drawable-hdpi/pull_to_refresh_flip.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-hdpi/pull_to_refresh_rotate.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sddyljsx/pulltorefresh/HEAD/app/src/main/res/drawable-hdpi/pull_to_refresh_rotate.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-xhdpi/pull_to_refresh_flip.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sddyljsx/pulltorefresh/HEAD/app/src/main/res/drawable-xhdpi/pull_to_refresh_flip.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-xhdpi/pull_to_refresh_rotate.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sddyljsx/pulltorefresh/HEAD/app/src/main/res/drawable-xhdpi/pull_to_refresh_rotate.png -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Wed Apr 10 15:27:10 PDT 2013 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-all.zip 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 下拉刷新 3 | 4 | 下拉刷新 5 | 释放立即刷新 6 | 正在刷新… 7 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/common_loading_progress_bar.xml: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 4 | 5 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 17 | 18 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 21 5 | buildToolsVersion "21.1.2" 6 | 7 | defaultConfig { 8 | applicationId "neal.pulltorefresh" 9 | minSdkVersion 8 10 | targetSdkVersion 21 11 | versionCode 1 12 | versionName "1.0" 13 | } 14 | buildTypes { 15 | release { 16 | minifyEnabled false 17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 18 | } 19 | } 20 | } 21 | 22 | dependencies { 23 | compile fileTree(dir: 'libs', include: ['*.jar']) 24 | compile 'com.android.support:appcompat-v7:21.0.2' 25 | } 26 | -------------------------------------------------------------------------------- /app/src/main/res/layout/image_list_item.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | 11 | 12 | 18 | -------------------------------------------------------------------------------- /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 D:\Android\sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 22 | -------------------------------------------------------------------------------- /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 -------------------------------------------------------------------------------- /pulltorefresh.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /app/src/main/res/layout/pull_to_refresh_footer_view.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 15 | 24 | 25 | -------------------------------------------------------------------------------- /app/src/main/java/neal/adapterview/core/FooterLayout.java: -------------------------------------------------------------------------------- 1 | package neal.adapterview.core; 2 | 3 | import android.content.Context; 4 | import android.util.AttributeSet; 5 | import android.view.LayoutInflater; 6 | import android.widget.FrameLayout; 7 | 8 | import neal.pulltorefresh.R; 9 | 10 | 11 | /** 12 | * Created by neal on 2014/12/23. 13 | */ 14 | public class FooterLayout extends FrameLayout { 15 | private Context context; 16 | public FooterLayout(Context context) { 17 | super(context); 18 | this.context=context; 19 | init(); 20 | } 21 | 22 | public FooterLayout(Context context, AttributeSet attrs) { 23 | super(context, attrs); 24 | this.context=context; 25 | init(); 26 | } 27 | 28 | public FooterLayout(Context context, AttributeSet attrs, int defStyle) { 29 | super(context, attrs, defStyle); 30 | this.context=context; 31 | init(); 32 | } 33 | 34 | public void init(){ 35 | LayoutInflater.from(context).inflate(R.layout.pull_to_refresh_footer_view, this); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /app/src/main/java/neal/adapterview/GridView.java: -------------------------------------------------------------------------------- 1 | package neal.adapterview; 2 | 3 | import android.content.Context; 4 | import android.util.AttributeSet; 5 | 6 | import neal.adapterview.core.PullToRefreshLayout; 7 | 8 | 9 | /** 10 | * Created by neal on 2014/12/23. 11 | */ 12 | public class GridView extends PullToRefreshLayout { 13 | private Context context; 14 | public GridView(Context context) { 15 | super(context); 16 | this.context=context; 17 | init(); 18 | } 19 | 20 | public GridView(Context context, AttributeSet attrs) { 21 | super(context, attrs); 22 | this.context=context; 23 | init(); 24 | } 25 | 26 | public GridView(Context context, AttributeSet attrs, int defStyle) { 27 | super(context, attrs, defStyle); 28 | this.context=context; 29 | init(); 30 | } 31 | @Override 32 | public void init() { 33 | setContentView(new android.widget.GridView(context)); 34 | super.init(); 35 | } 36 | public android.widget.GridView getGridView(){ 37 | return (android.widget.GridView)contentView; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /app/src/main/res/layout/common_loading_data_view.xml: -------------------------------------------------------------------------------- 1 | 2 | 13 | 14 | 20 | 28 | -------------------------------------------------------------------------------- /app/src/main/java/neal/adapterview/ListView.java: -------------------------------------------------------------------------------- 1 | package neal.adapterview; 2 | 3 | import android.content.Context; 4 | import android.util.AttributeSet; 5 | import android.view.View; 6 | 7 | import neal.adapterview.core.PullToRefreshLayout; 8 | import neal.utils.VersionUtil; 9 | 10 | 11 | /** 12 | * Created by neal on 2014/12/23. 13 | */ 14 | public class ListView extends PullToRefreshLayout { 15 | private Context context; 16 | public ListView(Context context) { 17 | super(context); 18 | this.context=context; 19 | init(); 20 | } 21 | 22 | public ListView(Context context, AttributeSet attrs) { 23 | super(context, attrs); 24 | this.context=context; 25 | init(); 26 | } 27 | 28 | public ListView(Context context, AttributeSet attrs, int defStyle) { 29 | super(context, attrs, defStyle); 30 | this.context=context; 31 | init(); 32 | } 33 | 34 | @Override 35 | public void init() { 36 | android.widget.ListView listView=new android.widget.ListView(context); 37 | listView.setDividerHeight(0); 38 | listView.setVerticalScrollBarEnabled(true); 39 | setContentView(listView); 40 | super.init(); 41 | } 42 | 43 | public android.widget.ListView getListView(){ 44 | return (android.widget.ListView)contentView; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 22 | 23 | 24 | 25 | 26 | 1.8 27 | 28 | 33 | 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /app/src/main/java/neal/utils/VersionUtil.java: -------------------------------------------------------------------------------- 1 | package neal.utils; 2 | 3 | import android.os.Build; 4 | 5 | /** 6 | * Created by Neal on 2014/10/30. 7 | */ 8 | public class VersionUtil { 9 | 10 | /** 11 | * 2.2 12 | */ 13 | public static boolean hasFroyo() { 14 | // Can use static final constants like FROYO, declared in later versions 15 | // of the OS since they are inlined at compile time. This is guaranteed behavior. 16 | return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO; 17 | } 18 | 19 | /** 20 | * 2.3 21 | */ 22 | public static boolean hasGingerbread() { 23 | return Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD; 24 | } 25 | 26 | /** 27 | * 3.0 28 | */ 29 | 30 | public static boolean hasHoneycomb() { 31 | return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB; 32 | } 33 | 34 | /** 35 | * 3.1 36 | */ 37 | public static boolean hasHoneycombMR1() { 38 | return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1; 39 | } 40 | 41 | /** 42 | * 3.2 43 | */ 44 | public static boolean hasHoneycombMR2() { 45 | return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2; 46 | } 47 | 48 | 49 | /** 50 | * 4.0 51 | */ 52 | public static boolean hasIceCreamSandwich() { 53 | return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH; 54 | } 55 | 56 | /** 57 | * 4.0.3 58 | */ 59 | public static boolean hasIceCreamSandwichMR1() { 60 | return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1; 61 | } 62 | 63 | /** 64 | * 4.1 65 | */ 66 | public static boolean hasJellyBean() { 67 | return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN; 68 | } 69 | 70 | /** 71 | * 4.4 72 | */ 73 | public static boolean hasKitKat() { 74 | return Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT; 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /app/src/main/res/layout/pull_to_refresh_header_view.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 12 | 13 | 20 | 21 | 29 | 30 | 36 | 37 | 38 | 43 | 44 | 49 | 50 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # pulltorefresh 2 | Android下拉刷新库,利用viewdraghelper实现 3 | 4 | 集成了下拉刷新,底部加载更多,以及刚进入加载数据的loadview。包括了listview与gridview的改写。 5 | 6 | 效果1: 7 | 8 | ![](https://github.com/sddyljsx/pulltorefresh/blob/master/001.png?raw=true) 9 | 10 | 11 | 效果2: 12 | 13 | ![](https://github.com/sddyljsx/pulltorefresh/blob/master/002.png?raw=true) 14 | 15 | 16 | 效果3: 17 | 18 | ![](https://github.com/sddyljsx/pulltorefresh/blob/master/003.png?raw=true) 19 | 20 | 21 | 效果4: 22 | 23 | ![](https://github.com/sddyljsx/pulltorefresh/blob/master/004.png?raw=true) 24 | 25 | 26 | 效果5: 27 | 28 | ![](https://github.com/sddyljsx/pulltorefresh/blob/master/005.png?raw=true) 29 | 30 | **使用说明:** 31 | 32 | 33 | imageList=(ListView)findViewById(R.id.image_list); 34 | imageAdapter=new ImageAdapter(); 35 | imageList.getListView().setAdapter(imageAdapter); 36 | imageList.setLoadDataListener(new PullToRefreshLayout.LoadDataListener() { 37 | @Override 38 | //下拉刷新调用 39 | public void onRefresh() { 40 | //模拟1秒的时间加载数据 41 | new Handler().postDelayed(new Runnable() { 42 | @Override 43 | public void run() { 44 | loadDate(true); 45 | } 46 | },1000); 47 | } 48 | 49 | @Override 50 | //下拉加载更多调用 51 | public void onLoadMore() { 52 | //模拟1秒的时间加载数据 53 | new Handler().postDelayed(new Runnable() { 54 | @Override 55 | public void run() { 56 | loadDate(false); 57 | } 58 | },1000); 59 | 60 | } 61 | }); 62 | //模拟1秒的时间加载数据 63 | new Handler().postDelayed(new Runnable() { 64 | @Override 65 | public void run() { 66 | loadDate(true); 67 | } 68 | },1000); 69 | 70 | } 71 | /** 72 | * 模拟加载数据 73 | * @param needFresh 是否需要刷新清空数据还是继续增加数据 74 | */ 75 | public void loadDate(final boolean needFresh){ 76 | 77 | //刷新,则清空数据 78 | if (needFresh) { 79 | listData.clear(); 80 | } 81 | //将新数据全部加入 82 | for(int i=0;iNUL 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/java/neal/adapterview/core/header/FlipLoadingLayout.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright 2011, 2012 Chris Banes. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | *******************************************************************************/ 16 | package neal.adapterview.core.header; 17 | 18 | import android.content.Context; 19 | import android.graphics.drawable.Drawable; 20 | import android.view.View; 21 | import android.view.animation.Animation; 22 | import android.view.animation.RotateAnimation; 23 | 24 | import neal.pulltorefresh.R; 25 | 26 | 27 | public class FlipLoadingLayout extends LoadingLayout { 28 | 29 | static final int FLIP_ANIMATION_DURATION = 150; 30 | 31 | private final Animation mRotateAnimation, mResetRotateAnimation; 32 | 33 | public FlipLoadingLayout(Context context) { 34 | super(context); 35 | final int rotateAngle = -180; 36 | 37 | mRotateAnimation = new RotateAnimation(0, rotateAngle, Animation.RELATIVE_TO_SELF, 0.5f, 38 | Animation.RELATIVE_TO_SELF, 0.5f); 39 | mRotateAnimation.setInterpolator(ANIMATION_INTERPOLATOR); 40 | mRotateAnimation.setDuration(FLIP_ANIMATION_DURATION); 41 | mRotateAnimation.setFillAfter(true); 42 | 43 | mResetRotateAnimation = new RotateAnimation(rotateAngle, 0, Animation.RELATIVE_TO_SELF, 0.5f, 44 | Animation.RELATIVE_TO_SELF, 0.5f); 45 | mResetRotateAnimation.setInterpolator(ANIMATION_INTERPOLATOR); 46 | mResetRotateAnimation.setDuration(FLIP_ANIMATION_DURATION); 47 | mResetRotateAnimation.setFillAfter(true); 48 | setImageDrawable(context.getResources().getDrawable(R.drawable.pull_to_refresh_flip)); 49 | } 50 | 51 | public void setImageDrawable(Drawable imageDrawable) { 52 | if (null != imageDrawable) { 53 | mHeaderImage.setImageDrawable(imageDrawable); 54 | } 55 | } 56 | 57 | 58 | @Override 59 | public void onPullToRefresh() { 60 | super.onPullToRefresh(); 61 | if (mRotateAnimation == mHeaderImage.getAnimation()) { 62 | mHeaderImage.startAnimation(mResetRotateAnimation); 63 | } 64 | } 65 | 66 | @Override 67 | public void onRefresh() { 68 | super.onRefresh(); 69 | mHeaderImage.clearAnimation(); 70 | mHeaderImage.setVisibility(View.INVISIBLE); 71 | mHeaderProgress.setVisibility(View.VISIBLE); 72 | } 73 | 74 | @Override 75 | public void onRefreshSlopReach() { 76 | super.onRefreshSlopReach(); 77 | mHeaderImage.startAnimation(mRotateAnimation); 78 | } 79 | 80 | @Override 81 | public void reset() { 82 | super.reset(); 83 | mHeaderImage.clearAnimation(); 84 | mHeaderProgress.setVisibility(View.GONE); 85 | mHeaderImage.setVisibility(View.VISIBLE); 86 | } 87 | 88 | } 89 | -------------------------------------------------------------------------------- /app/src/main/java/neal/adapterview/core/header/LoadingLayout.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright 2011, 2012 Chris Banes. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | *******************************************************************************/ 16 | package neal.adapterview.core.header; 17 | 18 | import android.content.Context; 19 | import android.graphics.drawable.Drawable; 20 | import android.text.TextUtils; 21 | import android.view.LayoutInflater; 22 | import android.view.View; 23 | import android.view.animation.Interpolator; 24 | import android.view.animation.LinearInterpolator; 25 | import android.widget.FrameLayout; 26 | import android.widget.ImageView; 27 | import android.widget.LinearLayout; 28 | import android.widget.ProgressBar; 29 | import android.widget.TextView; 30 | 31 | import neal.pulltorefresh.R; 32 | 33 | 34 | //下拉刷新基类 35 | public abstract class LoadingLayout extends FrameLayout { 36 | 37 | static final Interpolator ANIMATION_INTERPOLATOR = new LinearInterpolator(); 38 | private View mInnerLayout; 39 | //下拉刷新图片,进度条 40 | protected final ImageView mHeaderImage; 41 | protected final ProgressBar mHeaderProgress; 42 | //下拉刷新提示文字 43 | private final TextView mHeaderText; 44 | private final TextView mSubHeaderText; 45 | private CharSequence mPullLabel; 46 | private CharSequence mRefreshingLabel; 47 | private CharSequence mReleaseLabel; 48 | 49 | public LoadingLayout(Context context) { 50 | super(context); 51 | LayoutInflater.from(context).inflate(R.layout.pull_to_refresh_header_view, this); 52 | mInnerLayout = (View) findViewById(R.id.fl_inner); 53 | mHeaderText = (TextView) mInnerLayout.findViewById(R.id.pull_to_refresh_text); 54 | mHeaderProgress = (ProgressBar) mInnerLayout.findViewById(R.id.pull_to_refresh_progress); 55 | mSubHeaderText = (TextView) mInnerLayout.findViewById(R.id.pull_to_refresh_sub_text); 56 | mHeaderImage = (ImageView) mInnerLayout.findViewById(R.id.pull_to_refresh_image); 57 | // 提示文字 58 | mPullLabel = context.getString(R.string.pull_to_refresh_pull_label); 59 | mRefreshingLabel = context.getString(R.string.pull_to_refresh_refreshing_label); 60 | mReleaseLabel = context.getString(R.string.pull_to_refresh_release_label); 61 | reset(); 62 | } 63 | public void reset() { 64 | if (null != mHeaderText) { 65 | mHeaderText.setText(mPullLabel); 66 | } 67 | mHeaderImage.setVisibility(View.VISIBLE); 68 | 69 | if (null != mSubHeaderText) { 70 | if (TextUtils.isEmpty(mSubHeaderText.getText())) { 71 | mSubHeaderText.setVisibility(View.GONE); 72 | } else { 73 | mSubHeaderText.setVisibility(View.VISIBLE); 74 | } 75 | } 76 | } 77 | public void onPullToRefresh(){ 78 | if (null != mHeaderText) { 79 | mHeaderText.setText(mPullLabel); 80 | } 81 | }; 82 | public void onReleaseToClose(){ 83 | if (null != mHeaderText) { 84 | mHeaderText.setText(mPullLabel); 85 | } 86 | }; 87 | public void onRefreshSlopReach(){ 88 | if (null != mHeaderText) { 89 | mHeaderText.setText(mReleaseLabel); 90 | } 91 | }; 92 | public void onRefresh(){ 93 | if (null != mHeaderText) { 94 | mHeaderText.setText(mRefreshingLabel); 95 | } 96 | }; 97 | 98 | public final void setLoadingDrawable(Drawable imageDrawable) { 99 | 100 | mHeaderImage.setImageDrawable(imageDrawable); 101 | 102 | } 103 | 104 | private void setSubHeaderText(CharSequence label) { 105 | if (null != mSubHeaderText) { 106 | if (TextUtils.isEmpty(label)) { 107 | mSubHeaderText.setVisibility(View.GONE); 108 | } else { 109 | mSubHeaderText.setText(label); 110 | if (View.GONE == mSubHeaderText.getVisibility()) { 111 | mSubHeaderText.setVisibility(View.VISIBLE); 112 | } 113 | } 114 | } 115 | } 116 | 117 | } 118 | -------------------------------------------------------------------------------- /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 | # For Cygwin, ensure paths are in UNIX format before anything is touched. 46 | if $cygwin ; then 47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 48 | fi 49 | 50 | # Attempt to set APP_HOME 51 | # Resolve links: $0 may be a link 52 | PRG="$0" 53 | # Need this for relative symlinks. 54 | while [ -h "$PRG" ] ; do 55 | ls=`ls -ld "$PRG"` 56 | link=`expr "$ls" : '.*-> \(.*\)$'` 57 | if expr "$link" : '/.*' > /dev/null; then 58 | PRG="$link" 59 | else 60 | PRG=`dirname "$PRG"`"/$link" 61 | fi 62 | done 63 | SAVED="`pwd`" 64 | cd "`dirname \"$PRG\"`/" >&- 65 | APP_HOME="`pwd -P`" 66 | cd "$SAVED" >&- 67 | 68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 69 | 70 | # Determine the Java command to use to start the JVM. 71 | if [ -n "$JAVA_HOME" ] ; then 72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 73 | # IBM's JDK on AIX uses strange locations for the executables 74 | JAVACMD="$JAVA_HOME/jre/sh/java" 75 | else 76 | JAVACMD="$JAVA_HOME/bin/java" 77 | fi 78 | if [ ! -x "$JAVACMD" ] ; then 79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 80 | 81 | Please set the JAVA_HOME variable in your environment to match the 82 | location of your Java installation." 83 | fi 84 | else 85 | JAVACMD="java" 86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 87 | 88 | Please set the JAVA_HOME variable in your environment to match the 89 | location of your Java installation." 90 | fi 91 | 92 | # Increase the maximum file descriptors if we can. 93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 94 | MAX_FD_LIMIT=`ulimit -H -n` 95 | if [ $? -eq 0 ] ; then 96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 97 | MAX_FD="$MAX_FD_LIMIT" 98 | fi 99 | ulimit -n $MAX_FD 100 | if [ $? -ne 0 ] ; then 101 | warn "Could not set maximum file descriptor limit: $MAX_FD" 102 | fi 103 | else 104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 105 | fi 106 | fi 107 | 108 | # For Darwin, add options to specify how the application appears in the dock 109 | if $darwin; then 110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 111 | fi 112 | 113 | # For Cygwin, switch paths to Windows format before running java 114 | if $cygwin ; then 115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /app/app.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 8 | 9 | 10 | 11 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | -------------------------------------------------------------------------------- /app/src/main/java/neal/adapterview/core/PullToRefreshLayout.java: -------------------------------------------------------------------------------- 1 | package neal.adapterview.core; 2 | 3 | import android.content.Context; 4 | import android.support.v4.view.MotionEventCompat; 5 | import android.support.v4.view.ViewCompat; 6 | import android.util.AttributeSet; 7 | import android.view.MotionEvent; 8 | import android.view.View; 9 | import android.view.ViewGroup; 10 | import android.view.ViewTreeObserver; 11 | import android.widget.AbsListView; 12 | import android.widget.Adapter; 13 | import android.widget.FrameLayout; 14 | import android.widget.GridView; 15 | import android.widget.LinearLayout; 16 | import android.widget.ListView; 17 | 18 | 19 | import neal.adapterview.core.FooterLayout; 20 | import neal.adapterview.core.header.FlipLoadingLayout; 21 | import neal.pulltorefresh.R; 22 | import neal.utils.VersionUtil; 23 | 24 | 25 | /** 26 | * Created by neal on 2014/12/21. 27 | */ 28 | public class PullToRefreshLayout extends FrameLayout implements AbsListView.OnScrollListener { 29 | 30 | private Context context; 31 | 32 | private LinearLayout dragView; 33 | private ViewDragHelper mDragHelper; 34 | /** 35 | * 内容相关,头部,列表,底部 36 | */ 37 | private FlipLoadingLayout headerView; 38 | private FooterLayout footerView; 39 | protected AbsListView contentView; 40 | /** 41 | * 加载中视图 42 | */ 43 | private View loadingView; 44 | /** 45 | * 加载失败视图 46 | */ 47 | private View errorView; 48 | private int paddingTop=0; 49 | private int paddingBottom=0; 50 | //用户按屏幕时的初始点坐标 51 | private float initY; 52 | //现在的屏幕坐标点 53 | private float currentY=0; 54 | private float diffY=0; 55 | //现在所处的状态 56 | private State currentState; 57 | //最大可以下滑距离 58 | private int maxDragRange=0; 59 | //下拉刷新的临界值,超过该值,释放后刷新,否则不刷新 60 | private int refreshSlop=0; 61 | //是否已经到达临界值 62 | private boolean isRefreshSlopReach; 63 | //滑动过程中,现在的顶部位置 64 | private float currentTop=0; 65 | //是否在拖动 66 | private boolean isDragging; 67 | //是否还有更多数据需要加载 68 | private boolean hasMore; 69 | //是否允许下拉刷新 70 | private boolean isAllowPull=true; 71 | //是否显示加载更多 72 | private boolean isShowLoadMore=true; 73 | //是否现在初始加载界面 74 | private boolean isShowLoadView=true; 75 | private LoadDataListener loadDataListener; 76 | 77 | public PullToRefreshLayout(Context context) { 78 | super(context); 79 | this.context=context; 80 | } 81 | 82 | public PullToRefreshLayout(Context context, AttributeSet attrs) { 83 | super(context, attrs); 84 | this.context=context; 85 | } 86 | 87 | public PullToRefreshLayout(Context context, AttributeSet attrs, int defStyle) { 88 | super(context, attrs, defStyle); 89 | this.context=context; 90 | } 91 | 92 | public void setContentView(AbsListView contentView){ 93 | this.contentView=contentView; 94 | } 95 | 96 | public void setLoadDataListener(LoadDataListener loadDataListener){ 97 | this.loadDataListener=loadDataListener; 98 | } 99 | 100 | public void setIsAllowPull(boolean isAllowPull){ 101 | this.isAllowPull=isAllowPull; 102 | } 103 | public void setIsShowLoadMore(boolean isShowLoadMore){ 104 | this.isShowLoadMore=isShowLoadMore; 105 | } 106 | public void setIsShowLoadView(boolean isShowLoadView){ 107 | this.isShowLoadView=isShowLoadView; 108 | if(loadingView==null){ 109 | return; 110 | } 111 | if(isShowLoadView){ 112 | loadingView.setVisibility(View.VISIBLE); 113 | }else{ 114 | loadingView.setVisibility(View.GONE); 115 | } 116 | } 117 | 118 | 119 | public void init(){ 120 | dragView=new LinearLayout(context); 121 | dragView.setOrientation(LinearLayout.VERTICAL); 122 | headerView=new FlipLoadingLayout(context); 123 | footerView=new FooterLayout(context); 124 | addView(dragView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); 125 | dragView.addView(headerView,0,new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); 126 | LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0); 127 | lp.weight=1; 128 | dragView.addView(contentView,1,lp); 129 | contentView.setOnScrollListener(this); 130 | if(contentView instanceof ListView){ 131 | ((ListView) contentView).addFooterView(footerView); 132 | footerView.setVisibility(View.GONE); 133 | 134 | }else { 135 | dragView.addView(footerView, 2, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); 136 | footerView.setVisibility(View.GONE); 137 | } 138 | if(isShowLoadView) { 139 | loadingView = View.inflate(context, R.layout.common_loading_data_view, null); 140 | addView(loadingView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); 141 | } 142 | setState(State.CLOSE); 143 | 144 | ViewTreeObserver viewTreeObserver1 = headerView.getViewTreeObserver(); 145 | viewTreeObserver1.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { 146 | @Override 147 | public void onGlobalLayout() { 148 | if(VersionUtil.hasJellyBean()) { 149 | headerView.getViewTreeObserver().removeOnGlobalLayoutListener(this); 150 | }else { 151 | headerView.getViewTreeObserver().removeGlobalOnLayoutListener(this); 152 | } 153 | refreshSlop=headerView.getHeight()+10; 154 | paddingTop=-headerView.getHeight(); 155 | setPadding(getPaddingLeft(),paddingTop,getPaddingRight(),paddingBottom); 156 | //这样写只能呵呵 157 | scrollBy(0, -paddingTop); 158 | } 159 | }); 160 | 161 | ViewTreeObserver viewTreeObserver2 = contentView.getViewTreeObserver(); 162 | viewTreeObserver2.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { 163 | @Override 164 | public void onGlobalLayout() { 165 | if(VersionUtil.hasJellyBean()) { 166 | contentView.getViewTreeObserver().removeOnGlobalLayoutListener(this); 167 | }else { 168 | contentView.getViewTreeObserver().removeGlobalOnLayoutListener(this); 169 | } 170 | //listview高度2/3作为滑动范围 171 | maxDragRange=contentView.getHeight()*2/3; 172 | } 173 | }); 174 | 175 | 176 | mDragHelper = ViewDragHelper.create(this, 1f, new ViewDragHelper.Callback() { 177 | @Override 178 | public void onViewDragStateChanged(int state) { 179 | super.onViewDragStateChanged(state); 180 | } 181 | 182 | @Override 183 | public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) { 184 | //System.out.println(top); 185 | if(top<=0){ 186 | setState(State.CLOSE); 187 | } 188 | if(top<=headerView.getHeight()&¤tState==State.RELEASE_TO_REFRESH){ 189 | setState(State.REFRESHING); 190 | loadDataListener.onRefresh(); 191 | } 192 | currentTop=top; 193 | invalidate(); 194 | } 195 | 196 | @Override 197 | public void onViewCaptured(View capturedChild, int activePointerId) { 198 | super.onViewCaptured(capturedChild, activePointerId); 199 | } 200 | 201 | @Override 202 | public void onViewReleased(View releasedChild, float xvel, float yvel) { 203 | if(isRefreshSlopReach){ 204 | setState(State.RELEASE_TO_REFRESH); 205 | smoothSlideTo(headerView.getHeight()); 206 | //setState(State.REFRESHING); 207 | //loadDataListener.onRefresh(); 208 | 209 | }else { 210 | setState(State.RELEASE_TO_CLOSE); 211 | smoothSlideTo(0); 212 | setState(State.CLOSE); 213 | } 214 | 215 | invalidate(); 216 | 217 | } 218 | 219 | @Override 220 | public void onEdgeTouched(int edgeFlags, int pointerId) { 221 | super.onEdgeTouched(edgeFlags, pointerId); 222 | } 223 | 224 | @Override 225 | public boolean onEdgeLock(int edgeFlags) { 226 | return super.onEdgeLock(edgeFlags); 227 | } 228 | 229 | @Override 230 | public void onEdgeDragStarted(int edgeFlags, int pointerId) { 231 | super.onEdgeDragStarted(edgeFlags, pointerId); 232 | } 233 | 234 | @Override 235 | public int getOrderedChildIndex(int index) { 236 | return super.getOrderedChildIndex(index); 237 | } 238 | 239 | @Override 240 | public int getViewHorizontalDragRange(View child) { 241 | return super.getViewHorizontalDragRange(child); 242 | } 243 | 244 | @Override 245 | public int getViewVerticalDragRange(View child) { 246 | return maxDragRange; 247 | } 248 | 249 | @Override 250 | public boolean tryCaptureView(View child, int pointerId) { 251 | return child==dragView; 252 | } 253 | 254 | @Override 255 | public int clampViewPositionHorizontal(View child, int left, int dx) { 256 | return super.clampViewPositionHorizontal(child, left, dx); 257 | } 258 | 259 | @Override 260 | public int clampViewPositionVertical(View child, int top, int dy) { 261 | if(top>=refreshSlop && getDirection(dy)==Direction.DOWN){ 262 | isRefreshSlopReach=true; 263 | if(currentState==State.PULL_TO_REFRESH) { 264 | setState(State.REFRESH_SLOP_REACH); 265 | requestLayout(); 266 | } 267 | } 268 | if(top>maxDragRange){ 269 | return maxDragRange; 270 | } 271 | // System.out.println(top); 272 | return top; 273 | } 274 | }); 275 | 276 | } 277 | 278 | 279 | @Override 280 | //在diapatch中进行相应的事件的拦截 281 | public boolean dispatchTouchEvent(MotionEvent event) { 282 | if(!isAllowPull){ 283 | return super.dispatchTouchEvent(event); 284 | } 285 | final int action = MotionEventCompat.getActionMasked(event); 286 | //System.out.println(action); 287 | //正在刷新,果断拦截事件 288 | if(currentState==State.REFRESHING){ 289 | mDragHelper.processTouchEvent(event); 290 | return true; 291 | } 292 | switch (action){ 293 | case MotionEvent.ACTION_DOWN: { 294 | initY=event.getRawY(); 295 | //传入初始值,否则,直接传入ACTION_MOVE,会导致NullPointError 296 | mDragHelper.processTouchEvent(event); 297 | break; 298 | } 299 | //处理多指触控 300 | case MotionEvent.ACTION_POINTER_DOWN: { 301 | //传入初始值,否则,直接传入ACTION_MOVE,会导致NullPointError 302 | mDragHelper.processTouchEvent(event); 303 | break; 304 | } 305 | case MotionEvent.ACTION_MOVE: { 306 | currentY=event.getRawY(); 307 | diffY=currentY-initY; 308 | //到顶部,并且是向下拉 309 | if(isTopReached() && getDirection(diffY)==Direction.DOWN) { 310 | mDragHelper.processTouchEvent(event); 311 | if(currentState==State.CLOSE) { 312 | reset(); 313 | setState(State.PULL_TO_REFRESH); 314 | } 315 | //发送cancel事件,防止listview响应之前的事件,出现点击操作。 316 | event.setAction(MotionEvent.ACTION_CANCEL); 317 | super.dispatchTouchEvent(event); 318 | return true; 319 | } 320 | break; 321 | } 322 | case MotionEvent.ACTION_UP: { 323 | if(currentState!=State.CLOSE) { 324 | mDragHelper.processTouchEvent(event); 325 | } 326 | break; 327 | 328 | } 329 | 330 | case MotionEvent.ACTION_CANCEL: { 331 | 332 | break; 333 | 334 | } 335 | 336 | default:break; 337 | } 338 | 339 | return super.dispatchTouchEvent(event); 340 | 341 | } 342 | 343 | @Override 344 | public boolean onInterceptTouchEvent(MotionEvent event) { 345 | //不对事件做任何拦截 346 | return false; 347 | } 348 | 349 | @Override 350 | public boolean onTouchEvent(MotionEvent event) { 351 | 352 | return super.onTouchEvent(event); 353 | } 354 | 355 | @Override 356 | protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 357 | if(currentState==State.CLOSE || currentState==State.PULL_TO_REFRESH ) { 358 | super.onLayout(changed, left, top, right, bottom); 359 | }else { 360 | dragView.layout(left, (int) currentTop, right, (int) currentTop - paddingTop+bottom - top); 361 | } 362 | } 363 | 364 | boolean smoothSlideTo(int targetPosition) { 365 | if (mDragHelper.smoothSlideViewTo(dragView, dragView.getLeft(), targetPosition)) { 366 | ViewCompat.postInvalidateOnAnimation(this); 367 | return true; 368 | } 369 | return false; 370 | } 371 | //使smoothSlideViewTo起作用,必须要有此处 372 | @Override 373 | public void computeScroll() { 374 | 375 | if (mDragHelper != null && mDragHelper.continueSettling(true)) { 376 | 377 | ViewCompat.postInvalidateOnAnimation(this); 378 | } 379 | } 380 | 381 | private boolean isTopReached() { 382 | final Adapter adapter = contentView.getAdapter(); 383 | 384 | if (null == adapter || adapter.isEmpty()) { 385 | return true; 386 | 387 | } else { 388 | 389 | if (contentView.getFirstVisiblePosition() <= 1) { 390 | final View firstVisibleChild = contentView.getChildAt(0); 391 | if (firstVisibleChild != null) { 392 | //第一项已经到头并且还在继续向下拉 393 | return firstVisibleChild.getTop() >=0; 394 | } 395 | } 396 | } 397 | 398 | return false; 399 | } 400 | 401 | private boolean isBottomReached() { 402 | final Adapter adapter = contentView.getAdapter(); 403 | 404 | if (null == adapter || adapter.isEmpty()) { 405 | return true; 406 | 407 | } else { 408 | final int lastItemPosition = contentView.getCount() - 1; 409 | final int lastVisiblePosition = contentView.getLastVisiblePosition(); 410 | 411 | if (lastVisiblePosition >= lastItemPosition - 1) { 412 | final int childIndex = lastVisiblePosition - contentView.getFirstVisiblePosition(); 413 | final View lastVisibleChild = contentView.getChildAt(childIndex); 414 | if (lastVisibleChild != null) { 415 | //最后一项已经到头并继续向上拉 416 | return lastVisibleChild.getBottom() <= contentView.getHeight(); 417 | } 418 | } 419 | } 420 | 421 | return false; 422 | } 423 | 424 | public void reset(){ 425 | headerView.reset(); 426 | isRefreshSlopReach=false; 427 | } 428 | 429 | private void setState(State state){ 430 | 431 | currentState=state; 432 | 433 | switch (currentState){ 434 | case CLOSE:{ 435 | break; 436 | } 437 | case PULL_TO_REFRESH:{ 438 | headerView.onPullToRefresh(); 439 | break; 440 | } 441 | case REFRESH_SLOP_REACH:{ 442 | headerView.onRefreshSlopReach(); 443 | break; 444 | } 445 | case RELEASE_TO_CLOSE:{ 446 | headerView.onPullToRefresh(); 447 | break; 448 | } 449 | case RELEASE_TO_REFRESH:{ 450 | headerView.onRefresh(); 451 | break; 452 | } 453 | case REFRESHING:{ 454 | headerView.onRefresh(); 455 | /* if(contentView instanceof ListView){ 456 | footerView.setVisibility(View.VISIBLE); 457 | }*/ 458 | break; 459 | } 460 | } 461 | 462 | } 463 | 464 | Direction getDirection(float diffY){ 465 | if(diffY>1){ 466 | return Direction.DOWN; 467 | } 468 | if(diffY<-1){ 469 | return Direction.UP; 470 | } 471 | 472 | return Direction.UNKNOWN; 473 | 474 | } 475 | 476 | public enum Direction{ 477 | 478 | UNKNOWN(0), 479 | 480 | UP(1), 481 | 482 | DOWN(2); 483 | 484 | public int value; 485 | 486 | Direction(int intValue) { 487 | value = intValue; 488 | } 489 | 490 | int getValue() { 491 | return value; 492 | } 493 | 494 | } 495 | public enum State { 496 | 497 | CLOSE(0), 498 | 499 | PULL_TO_REFRESH(1), 500 | 501 | REFRESH_SLOP_REACH(2), 502 | 503 | RELEASE_TO_CLOSE(3), 504 | 505 | RELEASE_TO_REFRESH(4), 506 | 507 | REFRESHING(5); 508 | 509 | public int value; 510 | State(int intValue) { 511 | 512 | value = intValue; 513 | } 514 | 515 | int getValue() { 516 | 517 | return value; 518 | } 519 | 520 | } 521 | 522 | /** 523 | * 底部加载更多相关 524 | */ 525 | @Override 526 | public void onScrollStateChanged(AbsListView view, int scrollState) { 527 | 528 | //停止滑动 529 | if(scrollState==SCROLL_STATE_IDLE){ 530 | //到底部,加载更多 531 | if(isBottomReached()){ 532 | if(!hasMore) { 533 | return; 534 | } 535 | 536 | loadDataListener.onLoadMore(); 537 | if(!isShowLoadMore){ 538 | return; 539 | } 540 | footerView.setVisibility(View.VISIBLE); 541 | } 542 | 543 | } 544 | 545 | } 546 | 547 | @Override 548 | public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { 549 | 550 | 551 | } 552 | 553 | public interface LoadDataListener{ 554 | 555 | public abstract void onRefresh(); 556 | public abstract void onLoadMore(); 557 | 558 | } 559 | 560 | public void onLoadComplete(boolean isFresh, boolean hasMore){ 561 | this.hasMore=hasMore; 562 | if(!hasMore && contentView instanceof ListView){ 563 | footerView.setVisibility(View.GONE); 564 | } 565 | if(loadingView!=null && loadingView.getParent()==this){ 566 | removeView(loadingView); 567 | } 568 | if(isFresh) { 569 | if(!isAllowPull){ 570 | return; 571 | } 572 | smoothSlideTo(0); 573 | //setState(State.CLOSE); 574 | }else{ 575 | if(!isShowLoadMore){ 576 | return; 577 | } 578 | footerView.setVisibility(View.GONE); 579 | } 580 | 581 | } 582 | 583 | } 584 | -------------------------------------------------------------------------------- /app/src/main/java/neal/adapterview/core/ViewDragHelper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2013 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | package neal.adapterview.core; 19 | 20 | import android.content.Context; 21 | import android.support.v4.view.MotionEventCompat; 22 | import android.support.v4.view.VelocityTrackerCompat; 23 | import android.support.v4.view.ViewCompat; 24 | import android.support.v4.widget.ScrollerCompat; 25 | import android.view.MotionEvent; 26 | import android.view.VelocityTracker; 27 | import android.view.View; 28 | import android.view.ViewConfiguration; 29 | import android.view.ViewGroup; 30 | import android.view.animation.Interpolator; 31 | 32 | import java.util.Arrays; 33 | 34 | /** 35 | * ViewDragHelper is a utility class for writing custom ViewGroups. It offers a number 36 | * of useful operations and state tracking for allowing a user to drag and reposition 37 | * views within their parent ViewGroup. 38 | */ 39 | public class ViewDragHelper { 40 | private static final String TAG = "ViewDragHelper"; 41 | 42 | /** 43 | * A null/invalid pointer ID. 44 | */ 45 | public static final int INVALID_POINTER = -1; 46 | 47 | /** 48 | * A view is not currently being dragged or animating as a result of a fling/snap. 49 | */ 50 | public static final int STATE_IDLE = 0; 51 | 52 | /** 53 | * A view is currently being dragged. The position is currently changing as a result 54 | * of user input or simulated user input. 55 | */ 56 | public static final int STATE_DRAGGING = 1; 57 | 58 | /** 59 | * A view is currently settling into place as a result of a fling or 60 | * predefined non-interactive motion. 61 | */ 62 | public static final int STATE_SETTLING = 2; 63 | 64 | /** 65 | * Edge flag indicating that the left edge should be affected. 66 | */ 67 | public static final int EDGE_LEFT = 1 << 0; 68 | 69 | /** 70 | * Edge flag indicating that the right edge should be affected. 71 | */ 72 | public static final int EDGE_RIGHT = 1 << 1; 73 | 74 | /** 75 | * Edge flag indicating that the top edge should be affected. 76 | */ 77 | public static final int EDGE_TOP = 1 << 2; 78 | 79 | /** 80 | * Edge flag indicating that the bottom edge should be affected. 81 | */ 82 | public static final int EDGE_BOTTOM = 1 << 3; 83 | 84 | /** 85 | * Edge flag set indicating all edges should be affected. 86 | */ 87 | public static final int EDGE_ALL = EDGE_LEFT | EDGE_TOP | EDGE_RIGHT | EDGE_BOTTOM; 88 | 89 | /** 90 | * Indicates that a check should occur along the horizontal axis 91 | */ 92 | public static final int DIRECTION_HORIZONTAL = 1 << 0; 93 | 94 | /** 95 | * Indicates that a check should occur along the vertical axis 96 | */ 97 | public static final int DIRECTION_VERTICAL = 1 << 1; 98 | 99 | /** 100 | * Indicates that a check should occur along all axes 101 | */ 102 | public static final int DIRECTION_ALL = DIRECTION_HORIZONTAL | DIRECTION_VERTICAL; 103 | 104 | private static final int EDGE_SIZE = 20; // dp 105 | 106 | private static final int BASE_SETTLE_DURATION = 256; // ms 107 | private static final int MAX_SETTLE_DURATION = 600; // ms 108 | 109 | // Current drag state; idle, dragging or settling 110 | private int mDragState; 111 | 112 | // Distance to travel before a drag may begin 113 | private int mTouchSlop; 114 | 115 | // Last known position/pointer tracking 116 | private int mActivePointerId = INVALID_POINTER; 117 | private float[] mInitialMotionX; 118 | private float[] mInitialMotionY; 119 | private float[] mLastMotionX; 120 | private float[] mLastMotionY; 121 | private int[] mInitialEdgesTouched; 122 | private int[] mEdgeDragsInProgress; 123 | private int[] mEdgeDragsLocked; 124 | private int mPointersDown; 125 | 126 | private VelocityTracker mVelocityTracker; 127 | private float mMaxVelocity; 128 | private float mMinVelocity; 129 | 130 | private int mEdgeSize; 131 | private int mTrackingEdges; 132 | 133 | private ScrollerCompat mScroller; 134 | 135 | private final Callback mCallback; 136 | 137 | private View mCapturedView; 138 | private boolean mReleaseInProgress; 139 | 140 | private final ViewGroup mParentView; 141 | 142 | /** 143 | * A Callback is used as a communication channel with the ViewDragHelper back to the 144 | * parent view using it. on*methods are invoked on siginficant events and several 145 | * accessor methods are expected to provide the ViewDragHelper with more information 146 | * about the state of the parent view upon request. The callback also makes decisions 147 | * governing the range and draggability of child views. 148 | */ 149 | public static abstract class Callback { 150 | /** 151 | * Called when the drag state changes. See the STATE_* constants 152 | * for more information. 153 | * 154 | * @param state The new drag state 155 | * 156 | * @see #STATE_IDLE 157 | * @see #STATE_DRAGGING 158 | * @see #STATE_SETTLING 159 | */ 160 | public void onViewDragStateChanged(int state) {} 161 | 162 | /** 163 | * Called when the captured view's position changes as the result of a drag or settle. 164 | * 165 | * @param changedView View whose position changed 166 | * @param left New X coordinate of the left edge of the view 167 | * @param top New Y coordinate of the top edge of the view 168 | * @param dx Change in X position from the last call 169 | * @param dy Change in Y position from the last call 170 | */ 171 | public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {} 172 | 173 | /** 174 | * Called when a child view is captured for dragging or settling. The ID of the pointer 175 | * currently dragging the captured view is supplied. If activePointerId is 176 | * identified as {@link #INVALID_POINTER} the capture is programmatic instead of 177 | * pointer-initiated. 178 | * 179 | * @param capturedChild Child view that was captured 180 | * @param activePointerId Pointer id tracking the child capture 181 | */ 182 | public void onViewCaptured(View capturedChild, int activePointerId) {} 183 | 184 | /** 185 | * Called when the child view is no longer being actively dragged. 186 | * The fling velocity is also supplied, if relevant. The velocity values may 187 | * be clamped to system minimums or maximums. 188 | * 189 | *

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

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

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

283 | * 284 | *

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

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

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

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

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

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

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

1282 | * 1283 | * @param directions Combination of direction flags, see {@link #DIRECTION_HORIZONTAL}, 1284 | * {@link #DIRECTION_VERTICAL}, {@link #DIRECTION_ALL} 1285 | * @return true if the slop threshold has been crossed, false otherwise 1286 | */ 1287 | public boolean checkTouchSlop(int directions) { 1288 | final int count = mInitialMotionX.length; 1289 | for (int i = 0; i < count; i++) { 1290 | if (checkTouchSlop(directions, i)) { 1291 | return true; 1292 | } 1293 | } 1294 | return false; 1295 | } 1296 | 1297 | /** 1298 | * Check if the specified pointer tracked in the current gesture has crossed 1299 | * the required slop threshold. 1300 | * 1301 | *

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

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