├── .gitignore ├── README.md ├── app ├── build.gradle └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── laowch │ │ └── pulltoback │ │ └── ApplicationTest.java │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── com │ │ └── laowch │ │ └── pulltoback │ │ ├── AbstractPullToBackActivity.java │ │ ├── MainActivity.java │ │ ├── PullToBackLayout.java │ │ ├── ViewDragHelper.java │ │ └── sample │ │ ├── ListViewFragment.java │ │ ├── ScreenSlidePageFragment.java │ │ ├── ScrollViewFragment.java │ │ ├── SingleFragmentActivity.java │ │ └── ViewPagerFragment.java │ └── res │ ├── anim │ ├── fade_out.xml │ └── slide_in_bottom.xml │ ├── drawable-hdpi │ └── ic_launcher.png │ ├── drawable-mdpi │ └── ic_launcher.png │ ├── drawable-xhdpi │ └── ic_launcher.png │ ├── drawable-xxhdpi │ └── ic_launcher.png │ ├── layout │ ├── activity_main.xml │ ├── activity_simple.xml │ ├── fragment_listview.xml │ ├── fragment_screen_slide_page.xml │ ├── fragment_scrollview.xml │ ├── fragment_view_pager.xml │ └── simple_toolbar.xml │ ├── menu │ └── menu_main.xml │ ├── values-w820dp │ └── dimens.xml │ └── values │ ├── dimens.xml │ ├── strings.xml │ └── styles.xml ├── build.gradle ├── gradle.properties └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | # built application files 2 | *.apk 3 | *.ap_ 4 | *build/ 5 | 6 | # files for the dex VM 7 | *.dex 8 | 9 | # Java class files 10 | *.class 11 | 12 | # generated files 13 | bin/ 14 | gen/ 15 | 16 | # Local configuration file (sdk path, etc) 17 | local.properties 18 | 19 | # Eclipse project files 20 | .classpath 21 | .project 22 | 23 | # Proguard folder generated by Eclipse 24 | proguard/ 25 | *.pro 26 | 27 | # Intellij project files 28 | *.iml 29 | *.ipr 30 | *.iws 31 | .idea/ 32 | 33 | # Gradle files 34 | .gradle 35 | gradle 36 | gradlew* 37 | 38 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Android PullToBack effect like Inbox 2 | ========== 3 | 4 | This project implements a PullToBack effect like Inbox (A mail app by Google). 5 | 6 | ## Included Features 7 | 8 | - Supports both Pulling Down from the top, and Pulling Up from the bottom. 9 | - Animated Scrolling for all devices. 10 | - Currently works with: 11 | * **ListView** 12 | * **ScrollView** 13 | * **A form with EditText (You can assgin EditText as scroll child with the method PullToBackLayout.setScrollChild().)** 14 | * **Any other view can be scroll or not, in theory.(I dont test it.)** 15 | 16 | 17 | ## Known Issus 18 | 19 | - ~~To avoid misoperation, when you scroll the child view to the border and continue scroll, it should be stucked if you don't Up your finger.~~ (fixed) 20 | - ~~There's some conflicts with ViewPager.~~ (fixed) 21 | 22 | 23 | ## License 24 | 25 | Copyright 2013 laowch 26 | 27 | Licensed under the Apache License, Version 2.0 (the "License"); 28 | you may not use this file except in compliance with the License. 29 | You may obtain a copy of the License at 30 | 31 | http://www.apache.org/licenses/LICENSE-2.0 32 | 33 | Unless required by applicable law or agreed to in writing, software 34 | distributed under the License is distributed on an "AS IS" BASIS, 35 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 36 | See the License for the specific language governing permissions and 37 | limitations under the License. 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 21 5 | buildToolsVersion "21.1.1" 6 | 7 | defaultConfig { 8 | applicationId "com.laowch.pulltoback" 9 | minSdkVersion 7 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:support-v4:21.0.+' 25 | compile 'com.android.support:appcompat-v7:21.0.+' 26 | } 27 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/laowch/pulltoback/ApplicationTest.java: -------------------------------------------------------------------------------- 1 | package com.laowch.pulltoback; 2 | 3 | import android.app.Application; 4 | import android.test.ApplicationTestCase; 5 | 6 | /** 7 | * Testing Fundamentals 8 | */ 9 | public class ApplicationTest extends ApplicationTestCase { 10 | public ApplicationTest() { 11 | super(Application.class); 12 | } 13 | } -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 10 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /app/src/main/java/com/laowch/pulltoback/AbstractPullToBackActivity.java: -------------------------------------------------------------------------------- 1 | package com.laowch.pulltoback; 2 | 3 | import android.os.Bundle; 4 | import android.support.v7.app.ActionBarActivity; 5 | import android.view.View; 6 | import android.view.animation.AnimationUtils; 7 | import android.widget.TextView; 8 | 9 | /** 10 | * Created by lao on 14/11/30. 11 | */ 12 | public class AbstractPullToBackActivity extends ActionBarActivity { 13 | 14 | 15 | protected PullToBackLayout getPullToBackLayout() { 16 | return (PullToBackLayout) findViewById(R.id.pull_to_back_layout); 17 | } 18 | 19 | 20 | protected View getTitleView() { 21 | return findViewById(R.id.toolbar_title); 22 | } 23 | 24 | 25 | @Override 26 | public void setTitle(CharSequence title) { 27 | if (getTitleView() instanceof TextView) { 28 | ((TextView) getTitleView()).setText(title); 29 | } else { 30 | super.setTitle(title); 31 | } 32 | } 33 | 34 | @Override 35 | protected void onPostCreate(Bundle savedInstanceState) { 36 | super.onPostCreate(savedInstanceState); 37 | 38 | if (getPullToBackLayout() != null) { 39 | getPullToBackLayout().startAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_in_bottom)); 40 | } 41 | 42 | } 43 | 44 | 45 | } 46 | -------------------------------------------------------------------------------- /app/src/main/java/com/laowch/pulltoback/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.laowch.pulltoback; 2 | 3 | import android.content.Intent; 4 | import android.os.Bundle; 5 | import android.support.v7.app.ActionBarActivity; 6 | import android.support.v7.widget.Toolbar; 7 | import android.view.Menu; 8 | import android.view.MenuItem; 9 | import android.view.View; 10 | import android.widget.AdapterView; 11 | import android.widget.ArrayAdapter; 12 | import android.widget.ListView; 13 | 14 | import com.laowch.pulltoback.sample.ListViewFragment; 15 | import com.laowch.pulltoback.sample.ScrollViewFragment; 16 | import com.laowch.pulltoback.sample.SingleFragmentActivity; 17 | import com.laowch.pulltoback.sample.ViewPagerFragment; 18 | 19 | 20 | public class MainActivity extends ActionBarActivity implements AdapterView.OnItemClickListener { 21 | 22 | 23 | ListView listView; 24 | 25 | @Override 26 | protected void onCreate(Bundle savedInstanceState) { 27 | super.onCreate(savedInstanceState); 28 | setContentView(R.layout.activity_main); 29 | Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 30 | setSupportActionBar(toolbar); 31 | 32 | listView = (ListView) findViewById(R.id.list); 33 | 34 | listView.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, new String[]{ 35 | "ListView", "ScrollView", "ViewPager"})); 36 | 37 | listView.setOnItemClickListener(this); 38 | 39 | } 40 | 41 | 42 | @Override 43 | public boolean onCreateOptionsMenu(Menu menu) { 44 | // Inflate the menu; this adds items to the action bar if it is present. 45 | getMenuInflater().inflate(R.menu.menu_main, menu); 46 | return true; 47 | } 48 | 49 | @Override 50 | public boolean onOptionsItemSelected(MenuItem item) { 51 | // Handle action bar item clicks here. The action bar will 52 | // automatically handle clicks on the Home/Up button, so long 53 | // as you specify a parent activity in AndroidManifest.xml. 54 | int id = item.getItemId(); 55 | 56 | //noinspection SimplifiableIfStatement 57 | if (id == R.id.action_settings) { 58 | return true; 59 | } 60 | 61 | return super.onOptionsItemSelected(item); 62 | } 63 | 64 | @Override 65 | public void onItemClick(AdapterView parent, View view, int position, long id) { 66 | Intent intent = new Intent(this, SingleFragmentActivity.class); 67 | 68 | 69 | switch (position) { 70 | case 0: 71 | intent.putExtra(SingleFragmentActivity.EXTRA_FRAGMENT_NAME, ListViewFragment.class.getName()); 72 | startActivity(intent); 73 | break; 74 | case 1: 75 | intent.putExtra(SingleFragmentActivity.EXTRA_FRAGMENT_NAME, ScrollViewFragment.class.getName()); 76 | startActivity(intent); 77 | break; 78 | case 2: 79 | intent.putExtra(SingleFragmentActivity.EXTRA_FRAGMENT_NAME, ViewPagerFragment.class.getName()); 80 | startActivity(intent); 81 | break; 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /app/src/main/java/com/laowch/pulltoback/PullToBackLayout.java: -------------------------------------------------------------------------------- 1 | package com.laowch.pulltoback; 2 | 3 | import android.app.Activity; 4 | import android.content.Context; 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.widget.AbsListView; 11 | 12 | 13 | public class PullToBackLayout extends ViewGroup { 14 | 15 | 16 | public static int BACK_FACTOR = 3; 17 | 18 | private View target; 19 | 20 | private View scrollChild; 21 | 22 | private final ViewDragHelper dragHelper; 23 | 24 | private OnPullToBackListener onPullToBackListener; 25 | private OnDraggingBorderChangeListener onDraggingBorderChangeListener; 26 | 27 | boolean isBacking; 28 | 29 | private int verticalRange; 30 | 31 | private int draggingBorder; 32 | 33 | private int draggingState = 0; 34 | 35 | private final double AUTO_OPEN_SPEED_LIMIT = 800.0; 36 | 37 | 38 | public PullToBackLayout(Context context) { 39 | this(context, null); 40 | } 41 | 42 | 43 | public PullToBackLayout(Context context, AttributeSet attrs) { 44 | super(context, attrs); 45 | 46 | dragHelper = ViewDragHelper.create(this, 1.0f, new DragHelperCallback()); 47 | 48 | onPullToBackListener = new DefaultPullToBackListener(); 49 | 50 | onDraggingBorderChangeListener = new DefaultDraggingListener(); 51 | 52 | setWillNotDraw(false); 53 | 54 | setBackgroundColor(0xCC303030); 55 | } 56 | 57 | 58 | public boolean pullToBack() { 59 | ensureTarget(); 60 | isBacking = true; 61 | if (dragHelper.smoothSlideViewTo(target, 0, verticalRange)) { 62 | ViewCompat.postInvalidateOnAnimation(this); 63 | return true; 64 | } 65 | return false; 66 | } 67 | 68 | public void setScrollChild(View scrollChild) { 69 | this.scrollChild = scrollChild; 70 | } 71 | 72 | 73 | private void ensureTarget() { 74 | // Don't bother getting the parent height if the parent hasn't been laid out yet. 75 | if (target == null) { 76 | if (getChildCount() > 1 && !isInEditMode()) { 77 | throw new IllegalStateException( 78 | "SwipeRefreshLayout can host only one direct child"); 79 | } 80 | target = getChildAt(0); 81 | // mOriginalOffsetTop = target.getTop() + getPaddingTop(); 82 | 83 | if (scrollChild == null) { 84 | scrollChild = target; 85 | } 86 | } 87 | } 88 | 89 | 90 | @Override 91 | protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 92 | final int width = getMeasuredWidth(); 93 | final int height = getMeasuredHeight(); 94 | if (getChildCount() == 0) { 95 | return; 96 | } 97 | final View child = getChildAt(0); 98 | final int childLeft = getPaddingLeft(); 99 | final int childTop = getPaddingTop(); 100 | final int childWidth = width - getPaddingLeft() - getPaddingRight(); 101 | final int childHeight = height - getPaddingTop() - getPaddingBottom(); 102 | child.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight); 103 | } 104 | 105 | @Override 106 | public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 107 | super.onMeasure(widthMeasureSpec, heightMeasureSpec); 108 | if (getChildCount() > 1 && !isInEditMode()) { 109 | throw new IllegalStateException("SwipeRefreshLayout can host only one direct child"); 110 | } 111 | if (getChildCount() > 0) { 112 | getChildAt(0).measure( 113 | MeasureSpec.makeMeasureSpec( 114 | getMeasuredWidth() - getPaddingLeft() - getPaddingRight(), 115 | MeasureSpec.EXACTLY), 116 | MeasureSpec.makeMeasureSpec( 117 | getMeasuredHeight() - getPaddingTop() - getPaddingBottom(), 118 | MeasureSpec.EXACTLY)); 119 | } 120 | } 121 | 122 | /** 123 | * @return Whether it is possible for the child view of this layout to 124 | * scroll up. Override this if the child view is a custom view. 125 | */ 126 | public boolean canChildScrollUp() { 127 | if (android.os.Build.VERSION.SDK_INT < 14) { 128 | if (scrollChild instanceof AbsListView) { 129 | final AbsListView absListView = (AbsListView) scrollChild; 130 | return absListView.getChildCount() > 0 131 | && (absListView.getFirstVisiblePosition() > 0 || absListView.getChildAt(0) 132 | .getTop() < absListView.getPaddingTop()); 133 | } else { 134 | return scrollChild.getScrollY() > 0; 135 | } 136 | } else { 137 | return ViewCompat.canScrollVertically(scrollChild, -1); 138 | } 139 | } 140 | 141 | 142 | public boolean canChildScrollDown() { 143 | if (android.os.Build.VERSION.SDK_INT < 14) { 144 | // Does ViewCompat.canScrollVertically support api < 14 ? 145 | return ViewCompat.canScrollVertically(scrollChild, 1); 146 | } else { 147 | return ViewCompat.canScrollVertically(scrollChild, 1); 148 | } 149 | } 150 | 151 | @Override 152 | public boolean onInterceptTouchEvent(MotionEvent ev) { 153 | ensureTarget(); 154 | boolean handled = false; 155 | if (isEnabled() && !canChildScrollDown() || !canChildScrollUp()) { 156 | handled = dragHelper.shouldInterceptTouchEvent(ev); 157 | } else { 158 | dragHelper.cancel(); 159 | } 160 | return !handled ? super.onInterceptTouchEvent(ev) : handled; 161 | } 162 | 163 | @Override 164 | public boolean onTouchEvent(MotionEvent event) { 165 | dragHelper.processTouchEvent(event); 166 | return true; 167 | } 168 | 169 | public void setOnPullToBackListener(OnPullToBackListener onPullToBackListener) { 170 | this.onPullToBackListener = onPullToBackListener; 171 | } 172 | 173 | public void setOnDraggingListener(OnDraggingBorderChangeListener onDraggingBorderChangeListener) { 174 | this.onDraggingBorderChangeListener = onDraggingBorderChangeListener; 175 | } 176 | 177 | public interface OnPullToBackListener { 178 | public void onBack(); 179 | 180 | public void onShowTips(); 181 | 182 | public void onDismissTips(); 183 | } 184 | 185 | public interface OnDraggingBorderChangeListener { 186 | public void onDraggingTopChange(int top, int range); 187 | } 188 | 189 | 190 | public class DragHelperCallback extends ViewDragHelper.Callback { 191 | 192 | 193 | @Override 194 | public boolean tryCaptureView(View child, int pointerId) { 195 | return child == target; 196 | } 197 | 198 | @Override 199 | public void onViewDragStateChanged(int state) { 200 | if (state == draggingState) { // no change 201 | return; 202 | } 203 | if ((draggingState == ViewDragHelper.STATE_DRAGGING || draggingState == ViewDragHelper.STATE_SETTLING) && 204 | state == ViewDragHelper.STATE_IDLE) { 205 | // the view stopped from moving. 206 | 207 | if (draggingBorder == 0) { 208 | onStopDraggingToClosed(); 209 | } else if (draggingBorder == verticalRange) { 210 | 211 | if (onPullToBackListener != null) { 212 | onPullToBackListener.onBack(); 213 | } 214 | } 215 | } 216 | if (state == ViewDragHelper.STATE_DRAGGING) { 217 | onStartDragging(); 218 | } 219 | draggingState = state; 220 | } 221 | 222 | @Override 223 | public int getViewVerticalDragRange(View child) { 224 | return verticalRange; 225 | } 226 | 227 | @Override 228 | public int getViewHorizontalDragRange(View child) { 229 | return super.getViewHorizontalDragRange(child); 230 | } 231 | 232 | @Override 233 | public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) { 234 | draggingBorder = Math.abs(top); 235 | 236 | if (onPullToBackListener != null) { 237 | if (draggingBorder >= verticalRange / BACK_FACTOR) { 238 | onPullToBackListener.onShowTips(); 239 | } else { 240 | onPullToBackListener.onDismissTips(); 241 | } 242 | } 243 | 244 | if (onDraggingBorderChangeListener != null) { 245 | onDraggingBorderChangeListener.onDraggingTopChange(top, verticalRange); 246 | } 247 | } 248 | 249 | @Override 250 | public int clampViewPositionVertical(View child, int top, int dy) { 251 | int returnValue = 0; 252 | 253 | if (!canChildScrollUp() && top > 0) { 254 | final int topBound = getPaddingTop(); 255 | final int bottomBound = verticalRange; 256 | returnValue = Math.min(Math.max(top, topBound), bottomBound); 257 | } 258 | 259 | if (!canChildScrollDown() && top < 0) { 260 | final int topBound = -verticalRange; 261 | final int bottomBound = getPaddingTop(); 262 | returnValue = Math.min(Math.max(top, topBound), bottomBound); 263 | } 264 | 265 | return returnValue; 266 | } 267 | 268 | @Override 269 | public void onViewReleased(View releasedChild, float xvel, float yvel) { 270 | final float rangeToCheck = verticalRange; 271 | if (draggingBorder == 0) { 272 | return; 273 | } 274 | if (draggingBorder == rangeToCheck) { 275 | return; 276 | } 277 | boolean settleToOpen = false; 278 | if (Math.abs(yvel) > Math.abs(xvel)) { 279 | if (yvel > AUTO_OPEN_SPEED_LIMIT) { 280 | settleToOpen = !canChildScrollUp(); 281 | } else if (yvel < -AUTO_OPEN_SPEED_LIMIT) { 282 | settleToOpen = canChildScrollUp(); 283 | } 284 | } else if (draggingBorder >= rangeToCheck / BACK_FACTOR) { 285 | settleToOpen = true; 286 | } else if (draggingBorder < rangeToCheck / BACK_FACTOR) { 287 | settleToOpen = false; 288 | } 289 | 290 | int dest = !canChildScrollUp() ? verticalRange : -verticalRange; 291 | 292 | final int settleDestY = settleToOpen ? dest : 0; 293 | 294 | if (dragHelper.settleCapturedViewAt(0, settleDestY)) { 295 | ViewCompat.postInvalidateOnAnimation(PullToBackLayout.this); 296 | } 297 | } 298 | } 299 | 300 | 301 | private void onStartDragging() { 302 | 303 | } 304 | 305 | private void onStopDraggingToClosed() { 306 | 307 | } 308 | 309 | @Override 310 | public void computeScroll() { // needed for automatic settling. 311 | if (dragHelper.continueSettling(true)) { 312 | ViewCompat.postInvalidateOnAnimation(this); 313 | } 314 | } 315 | 316 | @Override 317 | protected void onSizeChanged(int w, int h, int oldw, int oldh) { 318 | super.onSizeChanged(w, h, oldw, oldh); 319 | verticalRange = h; 320 | } 321 | 322 | // default pull to back listener to control tips and activity exit animation. 323 | class DefaultPullToBackListener implements OnPullToBackListener { 324 | 325 | Activity activity; 326 | 327 | public DefaultPullToBackListener() { 328 | activity = (Activity) getContext(); 329 | } 330 | 331 | @Override 332 | public void onBack() { 333 | activity.finish(); 334 | activity.overridePendingTransition(0, R.anim.fade_out); 335 | } 336 | 337 | @Override 338 | public void onShowTips() { 339 | if (!isBacking) { 340 | activity.findViewById(R.id.back_tips).setVisibility(View.VISIBLE); 341 | } 342 | } 343 | 344 | @Override 345 | public void onDismissTips() { 346 | activity.findViewById(R.id.back_tips).setVisibility(View.GONE); 347 | } 348 | } 349 | 350 | // default dragging listener for background animation. 351 | class DefaultDraggingListener implements OnDraggingBorderChangeListener { 352 | 353 | @Override 354 | public void onDraggingTopChange(int top, int range) { 355 | float ratio = 1 - clamp(top * 2 / (float) range, 0f, 0.9f); 356 | PullToBackLayout.this.getBackground().setAlpha((int) (255 * ratio)); 357 | } 358 | } 359 | 360 | 361 | public static float clamp(float value, float min, float max) { 362 | return Math.max(min, Math.min(value, max)); 363 | } 364 | 365 | } -------------------------------------------------------------------------------- /app/src/main/java/com/laowch/pulltoback/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 com.laowch.pulltoback; 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(android.view.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 com.laowch.pulltoback.ViewDragHelper.Callback#onEdgeTouched(int, int)} and 428 | * {@link com.laowch.pulltoback.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 com.laowch.pulltoback.ViewDragHelper.Callback#tryCaptureView(android.view.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(android.view.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 | if (mInitialMotionX != null) { 508 | mInitialMotionX = null; 509 | } 510 | } 511 | 512 | /** 513 | * {@link #cancel()}, but also abort all motion in progress and snap to the end of any 514 | * animation. 515 | */ 516 | public void abort() { 517 | cancel(); 518 | if (mDragState == STATE_SETTLING) { 519 | final int oldX = mScroller.getCurrX(); 520 | final int oldY = mScroller.getCurrY(); 521 | mScroller.abortAnimation(); 522 | final int newX = mScroller.getCurrX(); 523 | final int newY = mScroller.getCurrY(); 524 | mCallback.onViewPositionChanged(mCapturedView, newX, newY, newX - oldX, newY - oldY); 525 | } 526 | setDragState(STATE_IDLE); 527 | } 528 | 529 | /** 530 | * Animate the view child to the given (left, top) position. 531 | * If this method returns true, the caller should invoke {@link #continueSettling(boolean)} 532 | * on each subsequent frame to continue the motion until it returns false. If this method 533 | * returns false there is no further work to do to complete the movement. 534 | * 535 | *

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

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

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

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

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

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

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

1333 | * 1334 | * @param directions Combination of direction flags, see {@link #DIRECTION_HORIZONTAL}, 1335 | * {@link #DIRECTION_VERTICAL}, {@link #DIRECTION_ALL} 1336 | * @param pointerId ID of the pointer to slop check as specified by MotionEvent 1337 | * @return true if the slop threshold has been crossed, false otherwise 1338 | */ 1339 | public boolean checkTouchSlop(int directions, int pointerId) { 1340 | if (!isPointerDown(pointerId)) { 1341 | return false; 1342 | } 1343 | 1344 | final boolean checkHorizontal = (directions & DIRECTION_HORIZONTAL) == DIRECTION_HORIZONTAL; 1345 | final boolean checkVertical = (directions & DIRECTION_VERTICAL) == DIRECTION_VERTICAL; 1346 | 1347 | final float dx = mLastMotionX[pointerId] - mInitialMotionX[pointerId]; 1348 | final float dy = mLastMotionY[pointerId] - mInitialMotionY[pointerId]; 1349 | 1350 | if (checkHorizontal && checkVertical) { 1351 | return dx * dx + dy * dy > mTouchSlop * mTouchSlop; 1352 | } else if (checkHorizontal) { 1353 | return Math.abs(dx) > mTouchSlop; 1354 | } else if (checkVertical) { 1355 | return Math.abs(dy) > mTouchSlop; 1356 | } 1357 | return false; 1358 | } 1359 | 1360 | /** 1361 | * Check if any of the edges specified were initially touched in the currently active gesture. 1362 | * If there is no currently active gesture this method will return false. 1363 | * 1364 | * @param edges Edges to check for an initial edge touch. See {@link #EDGE_LEFT}, 1365 | * {@link #EDGE_TOP}, {@link #EDGE_RIGHT}, {@link #EDGE_BOTTOM} and 1366 | * {@link #EDGE_ALL} 1367 | * @return true if any of the edges specified were initially touched in the current gesture 1368 | */ 1369 | public boolean isEdgeTouched(int edges) { 1370 | final int count = mInitialEdgesTouched.length; 1371 | for (int i = 0; i < count; i++) { 1372 | if (isEdgeTouched(edges, i)) { 1373 | return true; 1374 | } 1375 | } 1376 | return false; 1377 | } 1378 | 1379 | /** 1380 | * Check if any of the edges specified were initially touched by the pointer with 1381 | * the specified ID. If there is no currently active gesture or if there is no pointer with 1382 | * the given ID currently down this method will return false. 1383 | * 1384 | * @param edges Edges to check for an initial edge touch. See {@link #EDGE_LEFT}, 1385 | * {@link #EDGE_TOP}, {@link #EDGE_RIGHT}, {@link #EDGE_BOTTOM} and 1386 | * {@link #EDGE_ALL} 1387 | * @return true if any of the edges specified were initially touched in the current gesture 1388 | */ 1389 | public boolean isEdgeTouched(int edges, int pointerId) { 1390 | return isPointerDown(pointerId) && (mInitialEdgesTouched[pointerId] & edges) != 0; 1391 | } 1392 | 1393 | private void releaseViewForPointerUp() { 1394 | mVelocityTracker.computeCurrentVelocity(1000, mMaxVelocity); 1395 | final float xvel = clampMag( 1396 | VelocityTrackerCompat.getXVelocity(mVelocityTracker, mActivePointerId), 1397 | mMinVelocity, mMaxVelocity); 1398 | final float yvel = clampMag( 1399 | VelocityTrackerCompat.getYVelocity(mVelocityTracker, mActivePointerId), 1400 | mMinVelocity, mMaxVelocity); 1401 | dispatchViewReleased(xvel, yvel); 1402 | } 1403 | 1404 | private void dragTo(int left, int top, int dx, int dy) { 1405 | int clampedX = left; 1406 | int clampedY = top; 1407 | final int oldLeft = mCapturedView.getLeft(); 1408 | final int oldTop = mCapturedView.getTop(); 1409 | if (dx != 0) { 1410 | clampedX = mCallback.clampViewPositionHorizontal(mCapturedView, left, dx); 1411 | mCapturedView.offsetLeftAndRight(clampedX - oldLeft); 1412 | } 1413 | if (dy != 0) { 1414 | clampedY = mCallback.clampViewPositionVertical(mCapturedView, top, dy); 1415 | mCapturedView.offsetTopAndBottom(clampedY - oldTop); 1416 | } 1417 | 1418 | if (dx != 0 || dy != 0) { 1419 | final int clampedDx = clampedX - oldLeft; 1420 | final int clampedDy = clampedY - oldTop; 1421 | mCallback.onViewPositionChanged(mCapturedView, clampedX, clampedY, 1422 | clampedDx, clampedDy); 1423 | } 1424 | } 1425 | 1426 | /** 1427 | * Determine if the currently captured view is under the given point in the 1428 | * parent view's coordinate system. If there is no captured view this method 1429 | * will return false. 1430 | * 1431 | * @param x X position to test in the parent's coordinate system 1432 | * @param y Y position to test in the parent's coordinate system 1433 | * @return true if the captured view is under the given point, false otherwise 1434 | */ 1435 | public boolean isCapturedViewUnder(int x, int y) { 1436 | return isViewUnder(mCapturedView, x, y); 1437 | } 1438 | 1439 | /** 1440 | * Determine if the supplied view is under the given point in the 1441 | * parent view's coordinate system. 1442 | * 1443 | * @param view Child view of the parent to hit test 1444 | * @param x X position to test in the parent's coordinate system 1445 | * @param y Y position to test in the parent's coordinate system 1446 | * @return true if the supplied view is under the given point, false otherwise 1447 | */ 1448 | public boolean isViewUnder(View view, int x, int y) { 1449 | if (view == null) { 1450 | return false; 1451 | } 1452 | return x >= view.getLeft() && 1453 | x < view.getRight() && 1454 | y >= view.getTop() && 1455 | y < view.getBottom(); 1456 | } 1457 | 1458 | /** 1459 | * Find the topmost child under the given point within the parent view's coordinate system. 1460 | * The child order is determined using {@link com.laowch.pulltoback.ViewDragHelper.Callback#getOrderedChildIndex(int)}. 1461 | * 1462 | * @param x X position to test in the parent's coordinate system 1463 | * @param y Y position to test in the parent's coordinate system 1464 | * @return The topmost child view under (x, y) or null if none found. 1465 | */ 1466 | public View findTopChildUnder(int x, int y) { 1467 | final int childCount = mParentView.getChildCount(); 1468 | for (int i = childCount - 1; i >= 0; i--) { 1469 | final View child = mParentView.getChildAt(mCallback.getOrderedChildIndex(i)); 1470 | if (x >= child.getLeft() && x < child.getRight() && 1471 | y >= child.getTop() && y < child.getBottom()) { 1472 | return child; 1473 | } 1474 | } 1475 | return null; 1476 | } 1477 | 1478 | private int getEdgesTouched(int x, int y) { 1479 | int result = 0; 1480 | 1481 | if (x < mParentView.getLeft() + mEdgeSize) result |= EDGE_LEFT; 1482 | if (y < mParentView.getTop() + mEdgeSize) result |= EDGE_TOP; 1483 | if (x > mParentView.getRight() - mEdgeSize) result |= EDGE_RIGHT; 1484 | if (y > mParentView.getBottom() - mEdgeSize) result |= EDGE_BOTTOM; 1485 | 1486 | return result; 1487 | } 1488 | } -------------------------------------------------------------------------------- /app/src/main/java/com/laowch/pulltoback/sample/ListViewFragment.java: -------------------------------------------------------------------------------- 1 | package com.laowch.pulltoback.sample; 2 | 3 | import android.os.Bundle; 4 | import android.support.annotation.Nullable; 5 | import android.support.v4.app.Fragment; 6 | import android.view.LayoutInflater; 7 | import android.view.View; 8 | import android.view.ViewGroup; 9 | import android.widget.ArrayAdapter; 10 | import android.widget.ListView; 11 | 12 | import com.laowch.pulltoback.R; 13 | 14 | /** 15 | * Created by lao on 14/11/30. 16 | */ 17 | public class ListViewFragment extends Fragment { 18 | 19 | @Override 20 | public void onCreate(Bundle savedInstanceState) { 21 | super.onCreate(savedInstanceState); 22 | getActivity().setTitle("A Simple ListView"); 23 | } 24 | 25 | @Override 26 | public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 27 | View layout = inflater.inflate(R.layout.fragment_listview, container, false); 28 | 29 | ListView listView = (ListView) layout.findViewById(R.id.list); 30 | listView.setAdapter(new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, new String[]{ 31 | "Item 1", "Item 2", "Item 3", "Item 4", "Item 5", 32 | "Item 6", "Item 7", "Item 8", "Item 9", "Item 10", 33 | "Item 11", "Item 12", "Item 13", "Item 14", "Item 15"})); 34 | 35 | return layout; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /app/src/main/java/com/laowch/pulltoback/sample/ScreenSlidePageFragment.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.laowch.pulltoback.sample; 18 | 19 | 20 | import android.content.Context; 21 | import android.os.Bundle; 22 | import android.support.v4.app.Fragment; 23 | import android.view.LayoutInflater; 24 | import android.view.View; 25 | import android.view.ViewGroup; 26 | import android.widget.TextView; 27 | 28 | import com.laowch.pulltoback.R; 29 | 30 | 31 | public class ScreenSlidePageFragment extends Fragment { 32 | /** 33 | * The argument key for the page number this fragment represents. 34 | */ 35 | public static final String ARG_PAGE = "page"; 36 | 37 | /** 38 | * The fragment's page number, which is set to the argument value for {@link #ARG_PAGE}. 39 | */ 40 | private int mPageNumber; 41 | 42 | View scroll; 43 | 44 | /** 45 | * Factory method for this fragment class. Constructs a new fragment for the given page number. 46 | */ 47 | public static ScreenSlidePageFragment create(Context context, int pageNumber) { 48 | Bundle args = new Bundle(); 49 | args.putInt(ARG_PAGE, pageNumber); 50 | 51 | ScreenSlidePageFragment fragment = (ScreenSlidePageFragment) Fragment.instantiate(context, ScreenSlidePageFragment.class.getName(), args); 52 | 53 | return fragment; 54 | } 55 | 56 | public ScreenSlidePageFragment() { 57 | } 58 | 59 | @Override 60 | public void onCreate(Bundle savedInstanceState) { 61 | super.onCreate(savedInstanceState); 62 | mPageNumber = getArguments().getInt(ARG_PAGE); 63 | } 64 | 65 | @Override 66 | public View onCreateView(LayoutInflater inflater, ViewGroup container, 67 | Bundle savedInstanceState) { 68 | // Inflate the layout containing a title and body text. 69 | ViewGroup rootView = (ViewGroup) inflater 70 | .inflate(R.layout.fragment_screen_slide_page, container, false); 71 | 72 | scroll = rootView; 73 | 74 | // Set the title view to show the page number. 75 | ((TextView) rootView.findViewById(android.R.id.text1)).setText("Step" + (mPageNumber + 1)); 76 | 77 | return rootView; 78 | } 79 | 80 | /** 81 | * Returns the page number represented by this fragment object. 82 | */ 83 | public int getPageNumber() { 84 | return mPageNumber; 85 | } 86 | 87 | public View getScroll() { 88 | return scroll; 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /app/src/main/java/com/laowch/pulltoback/sample/ScrollViewFragment.java: -------------------------------------------------------------------------------- 1 | package com.laowch.pulltoback.sample; 2 | 3 | import android.os.Bundle; 4 | import android.support.annotation.Nullable; 5 | import android.support.v4.app.Fragment; 6 | import android.view.LayoutInflater; 7 | import android.view.View; 8 | import android.view.ViewGroup; 9 | 10 | import com.laowch.pulltoback.R; 11 | 12 | /** 13 | * Created by lao on 14/12/1. 14 | */ 15 | public class ScrollViewFragment extends Fragment { 16 | 17 | 18 | @Override 19 | public void onCreate(Bundle savedInstanceState) { 20 | super.onCreate(savedInstanceState); 21 | getActivity().setTitle("A Simple ScrollView"); 22 | } 23 | 24 | @Override 25 | public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 26 | View layout = inflater.inflate(R.layout.fragment_scrollview, container, false); 27 | return layout; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /app/src/main/java/com/laowch/pulltoback/sample/SingleFragmentActivity.java: -------------------------------------------------------------------------------- 1 | package com.laowch.pulltoback.sample; 2 | 3 | import android.content.Intent; 4 | import android.os.Bundle; 5 | import android.support.v4.app.Fragment; 6 | import android.support.v4.app.FragmentManager; 7 | import android.support.v4.app.FragmentTransaction; 8 | import android.support.v7.widget.Toolbar; 9 | 10 | import com.laowch.pulltoback.AbstractPullToBackActivity; 11 | import com.laowch.pulltoback.R; 12 | 13 | 14 | /** 15 | * @author Joosun 16 | * @since 2013-4-9 17 | */ 18 | public class SingleFragmentActivity extends AbstractPullToBackActivity { 19 | public static final String EXTRA_FRAGMENT_NAME = "extra_fragment_name"; 20 | 21 | public static final String EXTRA_FRAGMENT_EXTRAS = "extra_fragment_extras"; 22 | 23 | protected static final String TAG_SINGLE_FRAGMENT = "tag_single_fragment"; 24 | 25 | @Override 26 | protected void onCreate(final Bundle pSavedInstanceState) { 27 | super.onCreate(pSavedInstanceState); 28 | 29 | this.setContentView(R.layout.activity_simple); 30 | 31 | Toolbar toolbar = (Toolbar) findViewById(R.id.action_bar); 32 | setSupportActionBar(toolbar); 33 | getSupportActionBar().setDisplayHomeAsUpEnabled(true); 34 | getSupportActionBar().setDisplayShowTitleEnabled(false); 35 | 36 | final Intent intent = this.getIntent(); 37 | 38 | final FragmentManager fragmentManager = this.getSupportFragmentManager(); 39 | 40 | final Fragment fragment = fragmentManager.findFragmentByTag(SingleFragmentActivity.TAG_SINGLE_FRAGMENT); 41 | 42 | final String fragmentName = intent.getStringExtra(SingleFragmentActivity.EXTRA_FRAGMENT_NAME); 43 | 44 | final Bundle bundle = intent.getBundleExtra(SingleFragmentActivity.EXTRA_FRAGMENT_EXTRAS); 45 | 46 | if (fragment == null) { 47 | this.addFragment(fragmentName, bundle); 48 | } else { 49 | if (!fragment.getClass().getName().equals(fragmentName)) { 50 | final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); 51 | fragmentTransaction.remove(fragment); 52 | fragmentTransaction.commit(); 53 | 54 | this.addFragment(fragmentName, bundle); 55 | } 56 | } 57 | } 58 | 59 | 60 | @SuppressWarnings("unchecked") 61 | private void addFragment(final String pFragmentName, final Bundle pBundle) { 62 | try { 63 | final Class fragmentClass = (Class) Class.forName(pFragmentName); 64 | 65 | final FragmentManager fragmentManager = this.getSupportFragmentManager(); 66 | final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); 67 | 68 | final Fragment fragment = Fragment.instantiate(this, fragmentClass.getName(), pBundle); 69 | fragmentTransaction.add(R.id.content_frame, fragment, SingleFragmentActivity.TAG_SINGLE_FRAGMENT); 70 | fragmentTransaction.commit(); 71 | } catch (final ClassNotFoundException e) { 72 | e.printStackTrace(); 73 | } 74 | } 75 | 76 | 77 | } -------------------------------------------------------------------------------- /app/src/main/java/com/laowch/pulltoback/sample/ViewPagerFragment.java: -------------------------------------------------------------------------------- 1 | package com.laowch.pulltoback.sample; 2 | 3 | import android.os.Bundle; 4 | import android.support.annotation.Nullable; 5 | import android.support.v4.app.Fragment; 6 | import android.support.v4.app.FragmentManager; 7 | import android.support.v4.app.FragmentPagerAdapter; 8 | import android.support.v4.view.ViewPager; 9 | import android.view.LayoutInflater; 10 | import android.view.View; 11 | import android.view.ViewGroup; 12 | 13 | import com.laowch.pulltoback.PullToBackLayout; 14 | import com.laowch.pulltoback.R; 15 | 16 | import java.util.HashMap; 17 | import java.util.Map; 18 | 19 | /** 20 | * Created by lao on 14/12/9. 21 | */ 22 | public class ViewPagerFragment extends Fragment { 23 | 24 | PullToBackLayout layout; 25 | 26 | ViewPager pager; 27 | 28 | MyPagerAdapter adapter; 29 | 30 | 31 | @Override 32 | public void onCreate(Bundle savedInstanceState) { 33 | super.onCreate(savedInstanceState); 34 | getActivity().setTitle("A Simple ViewPager"); 35 | 36 | } 37 | 38 | @Override 39 | public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 40 | layout = (PullToBackLayout) inflater.inflate(R.layout.fragment_view_pager, container, false); 41 | 42 | pager = (ViewPager) layout.findViewById(R.id.pager); 43 | 44 | adapter = new MyPagerAdapter(getFragmentManager()); 45 | 46 | pager.setAdapter(adapter); 47 | 48 | pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { 49 | @Override 50 | public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { 51 | 52 | } 53 | 54 | @Override 55 | public void onPageSelected(int position) { 56 | ScreenSlidePageFragment fragment = (ScreenSlidePageFragment) adapter.getFragment(position); 57 | layout.setScrollChild(fragment.getScroll()); 58 | } 59 | 60 | @Override 61 | public void onPageScrollStateChanged(int state) { 62 | if (state == ViewPager.SCROLL_STATE_IDLE) { 63 | pager.requestDisallowInterceptTouchEvent(false); 64 | } else { 65 | pager.requestDisallowInterceptTouchEvent(true); 66 | } 67 | } 68 | }); 69 | 70 | pager.post(new Runnable() { 71 | @Override 72 | public void run() { 73 | ScreenSlidePageFragment fragment = (ScreenSlidePageFragment) adapter.getFragment(pager.getCurrentItem()); 74 | layout.setScrollChild(fragment.getScroll()); 75 | } 76 | }); 77 | 78 | return layout; 79 | } 80 | 81 | 82 | // A simple adapter can get Fragment by position. 83 | class MyPagerAdapter extends FragmentPagerAdapter { 84 | 85 | 86 | Map mFragmentTags; 87 | 88 | public MyPagerAdapter(FragmentManager fm) { 89 | super(fm); 90 | mFragmentTags = new HashMap(); 91 | } 92 | 93 | @Override 94 | public Fragment getItem(int i) { 95 | Fragment fragment = ScreenSlidePageFragment.create(getActivity(), i); 96 | return fragment; 97 | } 98 | 99 | @Override 100 | public int getCount() { 101 | return 10; 102 | } 103 | 104 | 105 | @Override 106 | public Object instantiateItem(ViewGroup container, int position) { 107 | Object obj = super.instantiateItem(container, position); 108 | if (obj instanceof Fragment) { 109 | // record the fragment tag here. 110 | Fragment f = (Fragment) obj; 111 | String tag = f.getTag(); 112 | mFragmentTags.put(position, tag); 113 | } 114 | return obj; 115 | } 116 | 117 | public Fragment getFragment(int position) { 118 | String tag = mFragmentTags.get(position); 119 | if (tag == null) 120 | return null; 121 | return getFragmentManager().findFragmentByTag(tag); 122 | } 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /app/src/main/res/anim/fade_out.xml: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /app/src/main/res/anim/slide_in_bottom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | s 9 | /> 10 | -------------------------------------------------------------------------------- /app/src/main/res/drawable-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/laowch/PullToBack/9c2ed7a0d636897a689b625ac7026aa5d5fb5370/app/src/main/res/drawable-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/laowch/PullToBack/9c2ed7a0d636897a689b625ac7026aa5d5fb5370/app/src/main/res/drawable-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/laowch/PullToBack/9c2ed7a0d636897a689b625ac7026aa5d5fb5370/app/src/main/res/drawable-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/laowch/PullToBack/9c2ed7a0d636897a689b625ac7026aa5d5fb5370/app/src/main/res/drawable-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 9 | 10 | 13 | 14 | 15 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_simple.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | 9 | 10 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /app/src/main/res/layout/fragment_listview.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 12 | 13 | -------------------------------------------------------------------------------- /app/src/main/res/layout/fragment_screen_slide_page.xml: -------------------------------------------------------------------------------- 1 | 16 | 17 | 21 | 22 | 23 | 27 | 28 | 34 | 35 | 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /app/src/main/res/layout/fragment_scrollview.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | 7 | 11 | 12 | 16 | 17 | 22 | 23 | 28 | 29 | 34 | 35 | 36 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /app/src/main/res/layout/fragment_view_pager.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 12 | 13 | -------------------------------------------------------------------------------- /app/src/main/res/layout/simple_toolbar.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 7 | 8 | 14 | 15 | 21 | 22 | 23 | 24 | 25 | 35 | -------------------------------------------------------------------------------- /app/src/main/res/menu/menu_main.xml: -------------------------------------------------------------------------------- 1 | 3 | 5 | 6 | -------------------------------------------------------------------------------- /app/src/main/res/values-w820dp/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 64dp 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16dp 4 | 16dp 5 | 18sp 6 | 56dp 7 | 8 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | PullToBack 5 | Hello world! 6 | Settings 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 9 | 10 | 11 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | repositories { 5 | jcenter() 6 | } 7 | dependencies { 8 | classpath 'com.android.tools.build:gradle:0.14.2' 9 | 10 | // NOTE: Do not place your application dependencies here; they belong 11 | // in the individual module build.gradle files 12 | } 13 | } 14 | 15 | allprojects { 16 | repositories { 17 | jcenter() 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /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 -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app' 2 | --------------------------------------------------------------------------------