ViewDragHelper.java 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580
  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. package me.imid.swipebacklayout.lib;
  17. import android.content.Context;
  18. import android.support.v4.view.MotionEventCompat;
  19. import android.support.v4.view.VelocityTrackerCompat;
  20. import android.support.v4.view.ViewCompat;
  21. import android.support.v4.widget.ScrollerCompat;
  22. import android.view.MotionEvent;
  23. import android.view.VelocityTracker;
  24. import android.view.View;
  25. import android.view.ViewConfiguration;
  26. import android.view.ViewGroup;
  27. import android.view.animation.Interpolator;
  28. import java.util.Arrays;
  29. /**
  30. * ViewDragHelper is a utility class for writing custom ViewGroups. It offers a
  31. * number of useful operations and state tracking for allowing a user to drag
  32. * and reposition views within their parent ViewGroup.
  33. */
  34. public class ViewDragHelper {
  35. private static final String TAG = "ViewDragHelper";
  36. /**
  37. * A null/invalid pointer ID.
  38. */
  39. public static final int INVALID_POINTER = -1;
  40. /**
  41. * A view is not currently being dragged or animating as a result of a
  42. * fling/snap.
  43. */
  44. public static final int STATE_IDLE = 0;
  45. /**
  46. * A view is currently being dragged. The position is currently changing as
  47. * a result of user input or simulated user input.
  48. */
  49. public static final int STATE_DRAGGING = 1;
  50. /**
  51. * A view is currently settling into place as a result of a fling or
  52. * predefined non-interactive motion.
  53. */
  54. public static final int STATE_SETTLING = 2;
  55. /**
  56. * Edge flag indicating that the left edge should be affected.
  57. */
  58. public static final int EDGE_LEFT = 1 << 0;
  59. /**
  60. * Edge flag indicating that the right edge should be affected.
  61. */
  62. public static final int EDGE_RIGHT = 1 << 1;
  63. /**
  64. * Edge flag indicating that the top edge should be affected.
  65. */
  66. public static final int EDGE_TOP = 1 << 2;
  67. /**
  68. * Edge flag indicating that the bottom edge should be affected.
  69. */
  70. public static final int EDGE_BOTTOM = 1 << 3;
  71. /**
  72. * Edge flag set indicating all edges should be affected.
  73. */
  74. public static final int EDGE_ALL = EDGE_LEFT | EDGE_TOP | EDGE_RIGHT | EDGE_BOTTOM;
  75. /**
  76. * Indicates that a check should occur along the horizontal axis
  77. */
  78. public static final int DIRECTION_HORIZONTAL = 1 << 0;
  79. /**
  80. * Indicates that a check should occur along the vertical axis
  81. */
  82. public static final int DIRECTION_VERTICAL = 1 << 1;
  83. /**
  84. * Indicates that a check should occur along all axes
  85. */
  86. public static final int DIRECTION_ALL = DIRECTION_HORIZONTAL | DIRECTION_VERTICAL;
  87. public static final int EDGE_SIZE = 20; // dp
  88. private static final int BASE_SETTLE_DURATION = 256; // ms
  89. private static final int MAX_SETTLE_DURATION = 600; // ms
  90. // Current drag state; idle, dragging or settling
  91. private int mDragState;
  92. // Distance to travel before a drag may begin
  93. private int mTouchSlop;
  94. // Last known position/pointer tracking
  95. private int mActivePointerId = INVALID_POINTER;
  96. private float[] mInitialMotionX;
  97. private float[] mInitialMotionY;
  98. private float[] mLastMotionX;
  99. private float[] mLastMotionY;
  100. private int[] mInitialEdgeTouched;
  101. private int[] mEdgeDragsInProgress;
  102. private int[] mEdgeDragsLocked;
  103. private int mPointersDown;
  104. private VelocityTracker mVelocityTracker;
  105. private float mMaxVelocity;
  106. private float mMinVelocity;
  107. private int mEdgeSize;
  108. private int mTrackingEdges;
  109. private ScrollerCompat mScroller;
  110. private final Callback mCallback;
  111. private View mCapturedView;
  112. private boolean mReleaseInProgress;
  113. private final ViewGroup mParentView;
  114. /**
  115. * A Callback is used as a communication channel with the ViewDragHelper
  116. * back to the parent view using it. <code>on*</code>methods are invoked on
  117. * siginficant events and several accessor methods are expected to provide
  118. * the ViewDragHelper with more information about the state of the parent
  119. * view upon request. The callback also makes decisions governing the range
  120. * and draggability of child views.
  121. */
  122. public static abstract class Callback {
  123. /**
  124. * Called when the drag state changes. See the <code>STATE_*</code>
  125. * constants for more information.
  126. *
  127. * @param state The new drag state
  128. * @see #STATE_IDLE
  129. * @see #STATE_DRAGGING
  130. * @see #STATE_SETTLING
  131. */
  132. public void onViewDragStateChanged(int state) {
  133. }
  134. /**
  135. * Called when the captured view's position changes as the result of a
  136. * drag or settle.
  137. *
  138. * @param changedView View whose position changed
  139. * @param left New X coordinate of the left edge of the view
  140. * @param top New Y coordinate of the top edge of the view
  141. * @param dx Change in X position from the last call
  142. * @param dy Change in Y position from the last call
  143. */
  144. public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
  145. }
  146. /**
  147. * Called when a child view is captured for dragging or settling. The ID
  148. * of the pointer currently dragging the captured view is supplied. If
  149. * activePointerId is identified as {@link #INVALID_POINTER} the capture
  150. * is programmatic instead of pointer-initiated.
  151. *
  152. * @param capturedChild Child view that was captured
  153. * @param activePointerId Pointer id tracking the child capture
  154. */
  155. public void onViewCaptured(View capturedChild, int activePointerId) {
  156. }
  157. /**
  158. * Called when the child view is no longer being actively dragged. The
  159. * fling velocity is also supplied, if relevant. The velocity values may
  160. * be clamped to system minimums or maximums.
  161. * <p>
  162. * Calling code may decide to fling or otherwise release the view to let
  163. * it settle into place. It should do so using
  164. * {@link #settleCapturedViewAt(int, int)} or
  165. * {@link #flingCapturedView(int, int, int, int)}. If the Callback
  166. * invokes one of these methods, the ViewDragHelper will enter
  167. * {@link #STATE_SETTLING} and the view capture will not fully end until
  168. * it comes to a complete stop. If neither of these methods is invoked
  169. * before <code>onViewReleased</code> returns, the view will stop in
  170. * place and the ViewDragHelper will return to {@link #STATE_IDLE}.
  171. * </p>
  172. *
  173. * @param releasedChild The captured child view now being released
  174. * @param xvel X velocity of the pointer as it left the screen in pixels
  175. * per second.
  176. * @param yvel Y velocity of the pointer as it left the screen in pixels
  177. * per second.
  178. */
  179. public void onViewReleased(View releasedChild, float xvel, float yvel) {
  180. }
  181. /**
  182. * Called when one of the subscribed edges in the parent view has been
  183. * touched by the user while no child view is currently captured.
  184. *
  185. * @param edgeFlags A combination of edge flags describing the edge(s)
  186. * currently touched
  187. * @param pointerId ID of the pointer touching the described edge(s)
  188. * @see #EDGE_LEFT
  189. * @see #EDGE_TOP
  190. * @see #EDGE_RIGHT
  191. * @see #EDGE_BOTTOM
  192. */
  193. public void onEdgeTouched(int edgeFlags, int pointerId) {
  194. }
  195. /**
  196. * Called when the given edge may become locked. This can happen if an
  197. * edge drag was preliminarily rejected before beginning, but after
  198. * {@link #onEdgeTouched(int, int)} was called. This method should
  199. * return true to lock this edge or false to leave it unlocked. The
  200. * default behavior is to leave edges unlocked.
  201. *
  202. * @param edgeFlags A combination of edge flags describing the edge(s)
  203. * locked
  204. * @return true to lock the edge, false to leave it unlocked
  205. */
  206. public boolean onEdgeLock(int edgeFlags) {
  207. return false;
  208. }
  209. /**
  210. * Called when the user has started a deliberate drag away from one of
  211. * the subscribed edges in the parent view while no child view is
  212. * currently captured.
  213. *
  214. * @param edgeFlags A combination of edge flags describing the edge(s)
  215. * dragged
  216. * @param pointerId ID of the pointer touching the described edge(s)
  217. * @see #EDGE_LEFT
  218. * @see #EDGE_TOP
  219. * @see #EDGE_RIGHT
  220. * @see #EDGE_BOTTOM
  221. */
  222. public void onEdgeDragStarted(int edgeFlags, int pointerId) {
  223. }
  224. /**
  225. * Called to determine the Z-order of child views.
  226. *
  227. * @param index the ordered position to query for
  228. * @return index of the view that should be ordered at position
  229. * <code>index</code>
  230. */
  231. public int getOrderedChildIndex(int index) {
  232. return index;
  233. }
  234. /**
  235. * Return the magnitude of a draggable child view's horizontal range of
  236. * motion in pixels. This method should return 0 for views that cannot
  237. * move horizontally.
  238. *
  239. * @param child Child view to check
  240. * @return range of horizontal motion in pixels
  241. */
  242. public int getViewHorizontalDragRange(View child) {
  243. return 0;
  244. }
  245. /**
  246. * Return the magnitude of a draggable child view's vertical range of
  247. * motion in pixels. This method should return 0 for views that cannot
  248. * move vertically.
  249. *
  250. * @param child Child view to check
  251. * @return range of vertical motion in pixels
  252. */
  253. public int getViewVerticalDragRange(View child) {
  254. return 0;
  255. }
  256. /**
  257. * Called when the user's input indicates that they want to capture the
  258. * given child view with the pointer indicated by pointerId. The
  259. * callback should return true if the user is permitted to drag the
  260. * given view with the indicated pointer.
  261. * <p>
  262. * ViewDragHelper may call this method multiple times for the same view
  263. * even if the view is already captured; this indicates that a new
  264. * pointer is trying to take control of the view.
  265. * </p>
  266. * <p>
  267. * If this method returns true, a call to
  268. * {@link #onViewCaptured(android.view.View, int)} will follow if the
  269. * capture is successful.
  270. * </p>
  271. *
  272. * @param child Child the user is attempting to capture
  273. * @param pointerId ID of the pointer attempting the capture
  274. * @return true if capture should be allowed, false otherwise
  275. */
  276. public abstract boolean tryCaptureView(View child, int pointerId);
  277. /**
  278. * Restrict the motion of the dragged child view along the horizontal
  279. * axis. The default implementation does not allow horizontal motion;
  280. * the extending class must override this method and provide the desired
  281. * clamping.
  282. *
  283. * @param child Child view being dragged
  284. * @param left Attempted motion along the X axis
  285. * @param dx Proposed change in position for left
  286. * @return The new clamped position for left
  287. */
  288. public int clampViewPositionHorizontal(View child, int left, int dx) {
  289. return 0;
  290. }
  291. /**
  292. * Restrict the motion of the dragged child view along the vertical
  293. * axis. The default implementation does not allow vertical motion; the
  294. * extending class must override this method and provide the desired
  295. * clamping.
  296. *
  297. * @param child Child view being dragged
  298. * @param top Attempted motion along the Y axis
  299. * @param dy Proposed change in position for top
  300. * @return The new clamped position for top
  301. */
  302. public int clampViewPositionVertical(View child, int top, int dy) {
  303. return 0;
  304. }
  305. }
  306. /**
  307. * Interpolator defining the animation curve for mScroller
  308. */
  309. private static final Interpolator sInterpolator = new Interpolator() {
  310. public float getInterpolation(float t) {
  311. t -= 1.0f;
  312. return t * t * t * t * t + 1.0f;
  313. }
  314. };
  315. private final Runnable mSetIdleRunnable = new Runnable() {
  316. public void run() {
  317. setDragState(STATE_IDLE);
  318. }
  319. };
  320. /**
  321. * Factory method to create a new ViewDragHelper.
  322. *
  323. * @param forParent Parent view to monitor
  324. * @param cb Callback to provide information and receive events
  325. * @return a new ViewDragHelper instance
  326. */
  327. public static ViewDragHelper create(ViewGroup forParent, Callback cb) {
  328. return new ViewDragHelper(forParent.getContext(), forParent, cb);
  329. }
  330. /**
  331. * Factory method to create a new ViewDragHelper.
  332. *
  333. * @param forParent Parent view to monitor
  334. * @param sensitivity Multiplier for how sensitive the helper should be
  335. * about detecting the start of a drag. Larger values are more
  336. * sensitive. 1.0f is normal.
  337. * @param cb Callback to provide information and receive events
  338. * @return a new ViewDragHelper instance
  339. */
  340. public static ViewDragHelper create(ViewGroup forParent, float sensitivity, Callback cb) {
  341. final ViewDragHelper helper = create(forParent, cb);
  342. helper.mTouchSlop = (int) (helper.mTouchSlop * (1 / sensitivity));
  343. return helper;
  344. }
  345. /**
  346. * Apps should use ViewDragHelper.create() to get a new instance. This will
  347. * allow VDH to use internal compatibility implementations for different
  348. * platform versions.
  349. *
  350. * @param context Context to initialize config-dependent params from
  351. * @param forParent Parent view to monitor
  352. */
  353. private ViewDragHelper(Context context, ViewGroup forParent, Callback cb) {
  354. if (forParent == null) {
  355. throw new IllegalArgumentException("Parent view may not be null");
  356. }
  357. if (cb == null) {
  358. throw new IllegalArgumentException("Callback may not be null");
  359. }
  360. mParentView = forParent;
  361. mCallback = cb;
  362. final ViewConfiguration vc = ViewConfiguration.get(context);
  363. final float density = context.getResources().getDisplayMetrics().density;
  364. mEdgeSize = (int) (EDGE_SIZE * density + 0.5f);
  365. mTouchSlop = vc.getScaledTouchSlop();
  366. mMaxVelocity = vc.getScaledMaximumFlingVelocity();
  367. mMinVelocity = vc.getScaledMinimumFlingVelocity();
  368. mScroller = ScrollerCompat.create(context, sInterpolator);
  369. }
  370. /**
  371. * Sets the sensitivity of the dragger.
  372. *
  373. * @param context The application context.
  374. * @param sensitivity value between 0 and 1, the final value for touchSlop =
  375. * ViewConfiguration.getScaledTouchSlop * (1 / s);
  376. */
  377. public void setSensitivity(Context context, float sensitivity) {
  378. float s = Math.max(0f, Math.min(1.0f, sensitivity));
  379. ViewConfiguration viewConfiguration = ViewConfiguration.get(context);
  380. mTouchSlop = (int) (viewConfiguration.getScaledTouchSlop() * (1 / s));
  381. }
  382. /**
  383. * Set the minimum velocity that will be detected as having a magnitude
  384. * greater than zero in pixels per second. Callback methods accepting a
  385. * velocity will be clamped appropriately.
  386. *
  387. * @param minVel minimum velocity to detect
  388. */
  389. public void setMinVelocity(float minVel) {
  390. mMinVelocity = minVel;
  391. }
  392. /**
  393. * Set the max velocity that will be detected as having a magnitude
  394. * greater than zero in pixels per second. Callback methods accepting a
  395. * velocity will be clamped appropriately.
  396. *
  397. * @param maxVel max velocity to detect
  398. */
  399. public void setMaxVelocity(float maxVel) {
  400. mMaxVelocity = maxVel;
  401. }
  402. /**
  403. * Return the currently configured minimum velocity. Any flings with a
  404. * magnitude less than this value in pixels per second. Callback methods
  405. * accepting a velocity will receive zero as a velocity value if the real
  406. * detected velocity was below this threshold.
  407. *
  408. * @return the minimum velocity that will be detected
  409. */
  410. public float getMinVelocity() {
  411. return mMinVelocity;
  412. }
  413. /**
  414. * Retrieve the current drag state of this helper. This will return one of
  415. * {@link #STATE_IDLE}, {@link #STATE_DRAGGING} or {@link #STATE_SETTLING}.
  416. *
  417. * @return The current drag state
  418. */
  419. public int getViewDragState() {
  420. return mDragState;
  421. }
  422. /**
  423. * Enable edge tracking for the selected edges of the parent view. The
  424. * callback's
  425. * {@link me.imid.swipebacklayout.lib.ViewDragHelper.Callback#onEdgeTouched(int, int)}
  426. * and
  427. * {@link me.imid.swipebacklayout.lib.ViewDragHelper.Callback#onEdgeDragStarted(int, int)}
  428. * methods will only be invoked for edges for which edge tracking has been
  429. * 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. * Return the size of an edge. This is the range in pixels along the edges
  442. * of this view that will actively detect edge touches or drags if edge
  443. * 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. * Set the size of an edge. This is the range in pixels along the edges of
  453. * this view that will actively detect edge touches or drags if edge
  454. * tracking is enabled.
  455. *
  456. * @param size The size of an edge in pixels
  457. */
  458. public void setEdgeSize(int size) {
  459. mEdgeSize = size;
  460. }
  461. /**
  462. * Capture a specific child view for dragging within the parent. The
  463. * callback will be notified but
  464. * {@link me.imid.swipebacklayout.lib.ViewDragHelper.Callback#tryCaptureView(android.view.View, int)}
  465. * will not be asked permission to capture this view.
  466. *
  467. * @param childView Child view to capture
  468. * @param activePointerId ID of the pointer that is dragging the captured
  469. * child view
  470. */
  471. public void captureChildView(View childView, int activePointerId) {
  472. if (childView.getParent() != mParentView) {
  473. throw new IllegalArgumentException("captureChildView: parameter must be a descendant "
  474. + "of the ViewDragHelper's tracked parent view (" + mParentView + ")");
  475. }
  476. mCapturedView = childView;
  477. mActivePointerId = activePointerId;
  478. mCallback.onViewCaptured(childView, activePointerId);
  479. setDragState(STATE_DRAGGING);
  480. }
  481. /**
  482. * @return The currently captured view, or null if no view has been
  483. * captured.
  484. */
  485. public View getCapturedView() {
  486. return mCapturedView;
  487. }
  488. /**
  489. * @return The ID of the pointer currently dragging the captured view, or
  490. * {@link #INVALID_POINTER}.
  491. */
  492. public int getActivePointerId() {
  493. return mActivePointerId;
  494. }
  495. /**
  496. * @return The minimum distance in pixels that the user must travel to
  497. * initiate a drag
  498. */
  499. public int getTouchSlop() {
  500. return mTouchSlop;
  501. }
  502. /**
  503. * The result of a call to this method is equivalent to
  504. * {@link #processTouchEvent(android.view.MotionEvent)} receiving an
  505. * ACTION_CANCEL event.
  506. */
  507. public void cancel() {
  508. mActivePointerId = INVALID_POINTER;
  509. clearMotionHistory();
  510. if (mVelocityTracker != null) {
  511. mVelocityTracker.recycle();
  512. mVelocityTracker = null;
  513. }
  514. }
  515. /**
  516. * {@link #cancel()}, but also abort all motion in progress and snap to the
  517. * end of any animation.
  518. */
  519. public void abort() {
  520. cancel();
  521. if (mDragState == STATE_SETTLING) {
  522. final int oldX = mScroller.getCurrX();
  523. final int oldY = mScroller.getCurrY();
  524. mScroller.abortAnimation();
  525. final int newX = mScroller.getCurrX();
  526. final int newY = mScroller.getCurrY();
  527. mCallback.onViewPositionChanged(mCapturedView, newX, newY, newX - oldX, newY - oldY);
  528. }
  529. setDragState(STATE_IDLE);
  530. }
  531. /**
  532. * Animate the view <code>child</code> to the given (left, top) position. If
  533. * this method returns true, the caller should invoke
  534. * {@link #continueSettling(boolean)} on each subsequent frame to continue
  535. * the motion until it returns false. If this method returns false there is
  536. * no further work to do to complete the movement.
  537. * <p>
  538. * This operation does not count as a capture event, though
  539. * {@link #getCapturedView()} will still report the sliding view while the
  540. * slide is in progress.
  541. * </p>
  542. *
  543. * @param child Child view to capture and animate
  544. * @param finalLeft Final left position of child
  545. * @param finalTop Final top position of child
  546. * @return true if animation should continue through
  547. * {@link #continueSettling(boolean)} calls
  548. */
  549. public boolean smoothSlideViewTo(View child, int finalLeft, int finalTop) {
  550. mCapturedView = child;
  551. mActivePointerId = INVALID_POINTER;
  552. return forceSettleCapturedViewAt(finalLeft, finalTop, 0, 0);
  553. }
  554. /**
  555. * Settle the captured view at the given (left, top) position. The
  556. * appropriate velocity from prior motion will be taken into account. If
  557. * this method returns true, the caller should invoke
  558. * {@link #continueSettling(boolean)} on each subsequent frame to continue
  559. * the motion until it returns false. If this method returns false there is
  560. * no further work to do to complete the movement.
  561. *
  562. * @param finalLeft Settled left edge position for the captured view
  563. * @param finalTop Settled top edge position for the captured view
  564. * @return true if animation should continue through
  565. * {@link #continueSettling(boolean)} calls
  566. */
  567. public boolean settleCapturedViewAt(int finalLeft, int finalTop) {
  568. if (!mReleaseInProgress) {
  569. throw new IllegalStateException("Cannot settleCapturedViewAt outside of a call to "
  570. + "Callback#onViewReleased");
  571. }
  572. return forceSettleCapturedViewAt(finalLeft, finalTop,
  573. (int) VelocityTrackerCompat.getXVelocity(mVelocityTracker, mActivePointerId),
  574. (int) VelocityTrackerCompat.getYVelocity(mVelocityTracker, mActivePointerId));
  575. }
  576. /**
  577. * Settle the captured view at the given (left, top) position.
  578. *
  579. * @param finalLeft Target left position for the captured view
  580. * @param finalTop Target top position for the captured view
  581. * @param xvel Horizontal velocity
  582. * @param yvel Vertical velocity
  583. * @return true if animation should continue through
  584. * {@link #continueSettling(boolean)} calls
  585. */
  586. private boolean forceSettleCapturedViewAt(int finalLeft, int finalTop, int xvel, int yvel) {
  587. final int startLeft = mCapturedView.getLeft();
  588. final int startTop = mCapturedView.getTop();
  589. final int dx = finalLeft - startLeft;
  590. final int dy = finalTop - startTop;
  591. if (dx == 0 && dy == 0) {
  592. // Nothing to do. Send callbacks, be done.
  593. mScroller.abortAnimation();
  594. setDragState(STATE_IDLE);
  595. return false;
  596. }
  597. final int duration = computeSettleDuration(mCapturedView, dx, dy, xvel, yvel);
  598. mScroller.startScroll(startLeft, startTop, dx, dy, duration);
  599. setDragState(STATE_SETTLING);
  600. return true;
  601. }
  602. private int computeSettleDuration(View child, int dx, int dy, int xvel, int yvel) {
  603. xvel = clampMag(xvel, (int) mMinVelocity, (int) mMaxVelocity);
  604. yvel = clampMag(yvel, (int) mMinVelocity, (int) mMaxVelocity);
  605. final int absDx = Math.abs(dx);
  606. final int absDy = Math.abs(dy);
  607. final int absXVel = Math.abs(xvel);
  608. final int absYVel = Math.abs(yvel);
  609. final int addedVel = absXVel + absYVel;
  610. final int addedDistance = absDx + absDy;
  611. final float xweight = xvel != 0 ? (float) absXVel / addedVel : (float) absDx
  612. / addedDistance;
  613. final float yweight = yvel != 0 ? (float) absYVel / addedVel : (float) absDy
  614. / addedDistance;
  615. int xduration = computeAxisDuration(dx, xvel, mCallback.getViewHorizontalDragRange(child));
  616. int yduration = computeAxisDuration(dy, yvel, mCallback.getViewVerticalDragRange(child));
  617. return (int) (xduration * xweight + yduration * yweight);
  618. }
  619. private int computeAxisDuration(int delta, int velocity, int motionRange) {
  620. if (delta == 0) {
  621. return 0;
  622. }
  623. final int width = mParentView.getWidth();
  624. final int halfWidth = width / 2;
  625. final float distanceRatio = Math.min(1f, (float) Math.abs(delta) / width);
  626. final float distance = halfWidth + halfWidth
  627. * distanceInfluenceForSnapDuration(distanceRatio);
  628. int duration;
  629. velocity = Math.abs(velocity);
  630. if (velocity > 0) {
  631. duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
  632. } else {
  633. final float range = (float) Math.abs(delta) / motionRange;
  634. duration = (int) ((range + 1) * BASE_SETTLE_DURATION);
  635. }
  636. return Math.min(duration, MAX_SETTLE_DURATION);
  637. }
  638. /**
  639. * Clamp the magnitude of value for absMin and absMax. If the value is below
  640. * the minimum, it will be clamped to zero. If the value is above the
  641. * maximum, it will be clamped to the maximum.
  642. *
  643. * @param value Value to clamp
  644. * @param absMin Absolute value of the minimum significant value to return
  645. * @param absMax Absolute value of the maximum value to return
  646. * @return The clamped value with the same sign as <code>value</code>
  647. */
  648. private int clampMag(int value, int absMin, int absMax) {
  649. final int absValue = Math.abs(value);
  650. if (absValue < absMin)
  651. return 0;
  652. if (absValue > absMax)
  653. return value > 0 ? absMax : -absMax;
  654. return value;
  655. }
  656. /**
  657. * Clamp the magnitude of value for absMin and absMax. If the value is below
  658. * the minimum, it will be clamped to zero. If the value is above the
  659. * maximum, it will be clamped to the maximum.
  660. *
  661. * @param value Value to clamp
  662. * @param absMin Absolute value of the minimum significant value to return
  663. * @param absMax Absolute value of the maximum value to return
  664. * @return The clamped value with the same sign as <code>value</code>
  665. */
  666. private float clampMag(float value, float absMin, float absMax) {
  667. final float absValue = Math.abs(value);
  668. if (absValue < absMin)
  669. return 0;
  670. if (absValue > absMax)
  671. return value > 0 ? absMax : -absMax;
  672. return value;
  673. }
  674. private float distanceInfluenceForSnapDuration(float f) {
  675. f -= 0.5f; // center the values about 0.
  676. f *= 0.3f * Math.PI / 2.0f;
  677. return (float) Math.sin(f);
  678. }
  679. /**
  680. * Settle the captured view based on standard free-moving fling behavior.
  681. * The caller should invoke {@link #continueSettling(boolean)} on each
  682. * subsequent frame to continue the motion until it returns false.
  683. *
  684. * @param minLeft Minimum X position for the view's left edge
  685. * @param minTop Minimum Y position for the view's top edge
  686. * @param maxLeft Maximum X position for the view's left edge
  687. * @param maxTop Maximum Y position for the view's top edge
  688. */
  689. public void flingCapturedView(int minLeft, int minTop, int maxLeft, int maxTop) {
  690. if (!mReleaseInProgress) {
  691. throw new IllegalStateException("Cannot flingCapturedView outside of a call to "
  692. + "Callback#onViewReleased");
  693. }
  694. mScroller.fling(mCapturedView.getLeft(), mCapturedView.getTop(),
  695. (int) VelocityTrackerCompat.getXVelocity(mVelocityTracker, mActivePointerId),
  696. (int) VelocityTrackerCompat.getYVelocity(mVelocityTracker, mActivePointerId),
  697. minLeft, maxLeft, minTop, maxTop);
  698. setDragState(STATE_SETTLING);
  699. }
  700. /**
  701. * Move the captured settling view by the appropriate amount for the current
  702. * time. If <code>continueSettling</code> returns true, the caller should
  703. * call it again on the next frame to continue.
  704. *
  705. * @param deferCallbacks true if state callbacks should be deferred via
  706. * posted message. Set this to true if you are calling this
  707. * method from {@link android.view.View#computeScroll()} or
  708. * similar methods invoked as part of layout or drawing.
  709. * @return true if settle is still in progress
  710. */
  711. public boolean continueSettling(boolean deferCallbacks) {
  712. if (mDragState == STATE_SETTLING) {
  713. boolean keepGoing = mScroller.computeScrollOffset();
  714. final int x = mScroller.getCurrX();
  715. final int y = mScroller.getCurrY();
  716. final int dx = x - mCapturedView.getLeft();
  717. final int dy = y - mCapturedView.getTop();
  718. if (dx != 0) {
  719. mCapturedView.offsetLeftAndRight(dx);
  720. }
  721. if (dy != 0) {
  722. mCapturedView.offsetTopAndBottom(dy);
  723. }
  724. if (dx != 0 || dy != 0) {
  725. mCallback.onViewPositionChanged(mCapturedView, x, y, dx, dy);
  726. }
  727. if (keepGoing && x == mScroller.getFinalX() && y == mScroller.getFinalY()) {
  728. // Close enough. The interpolator/scroller might think we're
  729. // still moving
  730. // but the user sure doesn't.
  731. mScroller.abortAnimation();
  732. keepGoing = mScroller.isFinished();
  733. }
  734. if (!keepGoing) {
  735. if (deferCallbacks) {
  736. mParentView.post(mSetIdleRunnable);
  737. } else {
  738. setDragState(STATE_IDLE);
  739. }
  740. }
  741. }
  742. return mDragState == STATE_SETTLING;
  743. }
  744. /**
  745. * Like all callback events this must happen on the UI thread, but release
  746. * involves some extra semantics. During a release (mReleaseInProgress) is
  747. * the only time it is valid to call {@link #settleCapturedViewAt(int, int)}
  748. * or {@link #flingCapturedView(int, int, int, int)}.
  749. */
  750. private void dispatchViewReleased(float xvel, float yvel) {
  751. mReleaseInProgress = true;
  752. mCallback.onViewReleased(mCapturedView, xvel, yvel);
  753. mReleaseInProgress = false;
  754. if (mDragState == STATE_DRAGGING) {
  755. // onViewReleased didn't call a method that would have changed this.
  756. // Go idle.
  757. setDragState(STATE_IDLE);
  758. }
  759. }
  760. private void clearMotionHistory() {
  761. if (mInitialMotionX == null) {
  762. return;
  763. }
  764. Arrays.fill(mInitialMotionX, 0);
  765. Arrays.fill(mInitialMotionY, 0);
  766. Arrays.fill(mLastMotionX, 0);
  767. Arrays.fill(mLastMotionY, 0);
  768. Arrays.fill(mInitialEdgeTouched, 0);
  769. Arrays.fill(mEdgeDragsInProgress, 0);
  770. Arrays.fill(mEdgeDragsLocked, 0);
  771. mPointersDown = 0;
  772. }
  773. private void clearMotionHistory(int pointerId) {
  774. if (mInitialMotionX == null) {
  775. return;
  776. }
  777. mInitialMotionX[pointerId] = 0;
  778. mInitialMotionY[pointerId] = 0;
  779. mLastMotionX[pointerId] = 0;
  780. mLastMotionY[pointerId] = 0;
  781. mInitialEdgeTouched[pointerId] = 0;
  782. mEdgeDragsInProgress[pointerId] = 0;
  783. mEdgeDragsLocked[pointerId] = 0;
  784. mPointersDown &= ~(1 << pointerId);
  785. }
  786. private void ensureMotionHistorySizeForId(int pointerId) {
  787. if (mInitialMotionX == null || mInitialMotionX.length <= pointerId) {
  788. float[] imx = new float[pointerId + 1];
  789. float[] imy = new float[pointerId + 1];
  790. float[] lmx = new float[pointerId + 1];
  791. float[] lmy = new float[pointerId + 1];
  792. int[] iit = new int[pointerId + 1];
  793. int[] edip = new int[pointerId + 1];
  794. int[] edl = new int[pointerId + 1];
  795. if (mInitialMotionX != null) {
  796. System.arraycopy(mInitialMotionX, 0, imx, 0, mInitialMotionX.length);
  797. System.arraycopy(mInitialMotionY, 0, imy, 0, mInitialMotionY.length);
  798. System.arraycopy(mLastMotionX, 0, lmx, 0, mLastMotionX.length);
  799. System.arraycopy(mLastMotionY, 0, lmy, 0, mLastMotionY.length);
  800. System.arraycopy(mInitialEdgeTouched, 0, iit, 0, mInitialEdgeTouched.length);
  801. System.arraycopy(mEdgeDragsInProgress, 0, edip, 0, mEdgeDragsInProgress.length);
  802. System.arraycopy(mEdgeDragsLocked, 0, edl, 0, mEdgeDragsLocked.length);
  803. }
  804. mInitialMotionX = imx;
  805. mInitialMotionY = imy;
  806. mLastMotionX = lmx;
  807. mLastMotionY = lmy;
  808. mInitialEdgeTouched = iit;
  809. mEdgeDragsInProgress = edip;
  810. mEdgeDragsLocked = edl;
  811. }
  812. }
  813. private void saveInitialMotion(float x, float y, int pointerId) {
  814. ensureMotionHistorySizeForId(pointerId);
  815. mInitialMotionX[pointerId] = mLastMotionX[pointerId] = x;
  816. mInitialMotionY[pointerId] = mLastMotionY[pointerId] = y;
  817. mInitialEdgeTouched[pointerId] = getEdgeTouched((int) x, (int) y);
  818. mPointersDown |= 1 << pointerId;
  819. }
  820. private void saveLastMotion(MotionEvent ev) {
  821. final int pointerCount = MotionEventCompat.getPointerCount(ev);
  822. for (int i = 0; i < pointerCount; i++) {
  823. final int pointerId = MotionEventCompat.getPointerId(ev, i);
  824. final float x = MotionEventCompat.getX(ev, i);
  825. final float y = MotionEventCompat.getY(ev, i);
  826. mLastMotionX[pointerId] = x;
  827. mLastMotionY[pointerId] = y;
  828. }
  829. }
  830. /**
  831. * Check if the given pointer ID represents a pointer that is currently down
  832. * (to the best of the ViewDragHelper's knowledge).
  833. * <p>
  834. * The state used to report this information is populated by the methods
  835. * {@link #shouldInterceptTouchEvent(android.view.MotionEvent)} or
  836. * {@link #processTouchEvent(android.view.MotionEvent)}. If one of these
  837. * methods has not been called for all relevant MotionEvents to track, the
  838. * information reported by this method may be stale or incorrect.
  839. * </p>
  840. *
  841. * @param pointerId pointer ID to check; corresponds to IDs provided by
  842. * MotionEvent
  843. * @return true if the pointer with the given ID is still down
  844. */
  845. public boolean isPointerDown(int pointerId) {
  846. return (mPointersDown & 1 << pointerId) != 0;
  847. }
  848. void setDragState(int state) {
  849. if (mDragState != state) {
  850. mDragState = state;
  851. mCallback.onViewDragStateChanged(state);
  852. if (state == STATE_IDLE) {
  853. mCapturedView = null;
  854. }
  855. }
  856. }
  857. /**
  858. * Attempt to capture the view with the given pointer ID. The callback will
  859. * be involved. This will put us into the "dragging" state. If we've already
  860. * captured this view with this pointer this method will immediately return
  861. * true without consulting the callback.
  862. *
  863. * @param toCapture View to capture
  864. * @param pointerId Pointer to capture with
  865. * @return true if capture was successful
  866. */
  867. boolean tryCaptureViewForDrag(View toCapture, int pointerId) {
  868. if (toCapture == mCapturedView && mActivePointerId == pointerId) {
  869. // Already done!
  870. return true;
  871. }
  872. if (toCapture != null && mCallback.tryCaptureView(toCapture, pointerId)) {
  873. mActivePointerId = pointerId;
  874. captureChildView(toCapture, pointerId);
  875. return true;
  876. }
  877. return false;
  878. }
  879. /**
  880. * Tests scrollability within child views of v given a delta of dx.
  881. *
  882. * @param v View to test for horizontal scrollability
  883. * @param checkV Whether the view v passed should itself be checked for
  884. * scrollability (true), or just its children (false).
  885. * @param dx Delta scrolled in pixels along the X axis
  886. * @param dy Delta scrolled in pixels along the Y axis
  887. * @param x X coordinate of the active touch point
  888. * @param y Y coordinate of the active touch point
  889. * @return true if child views of v can be scrolled by delta of dx.
  890. */
  891. protected boolean canScroll(View v, boolean checkV, int dx, int dy, int x, int y) {
  892. if (v instanceof ViewGroup) {
  893. final ViewGroup group = (ViewGroup) v;
  894. final int scrollX = v.getScrollX();
  895. final int scrollY = v.getScrollY();
  896. final int count = group.getChildCount();
  897. // Count backwards - let topmost views consume scroll distance
  898. // first.
  899. for (int i = count - 1; i >= 0; i--) {
  900. // TODO: Add versioned support here for transformed views.
  901. // This will not work for transformed views in Honeycomb+
  902. final View child = group.getChildAt(i);
  903. if (x + scrollX >= child.getLeft()
  904. && x + scrollX < child.getRight()
  905. && y + scrollY >= child.getTop()
  906. && y + scrollY < child.getBottom()
  907. && canScroll(child, true, dx, dy, x + scrollX - child.getLeft(), y
  908. + scrollY - child.getTop())) {
  909. return true;
  910. }
  911. }
  912. }
  913. return checkV
  914. && (ViewCompat.canScrollHorizontally(v, -dx) || ViewCompat.canScrollVertically(v,
  915. -dy));
  916. }
  917. /**
  918. * Check if this event as provided to the parent view's
  919. * onInterceptTouchEvent should cause the parent to intercept the touch
  920. * event stream.
  921. *
  922. * @param ev MotionEvent provided to onInterceptTouchEvent
  923. * @return true if the parent view should return true from
  924. * onInterceptTouchEvent
  925. */
  926. public boolean shouldInterceptTouchEvent(MotionEvent ev) {
  927. final int action = MotionEventCompat.getActionMasked(ev);
  928. final int actionIndex = MotionEventCompat.getActionIndex(ev);
  929. if (action == MotionEvent.ACTION_DOWN) {
  930. // Reset things for a new event stream, just in case we didn't get
  931. // the whole previous stream.
  932. cancel();
  933. }
  934. if (mVelocityTracker == null) {
  935. mVelocityTracker = VelocityTracker.obtain();
  936. }
  937. mVelocityTracker.addMovement(ev);
  938. switch (action) {
  939. case MotionEvent.ACTION_DOWN: {
  940. final float x = ev.getX();
  941. final float y = ev.getY();
  942. final int pointerId = MotionEventCompat.getPointerId(ev, 0);
  943. saveInitialMotion(x, y, pointerId);
  944. final View toCapture = findTopChildUnder((int) x, (int) y);
  945. // Catch a settling view if possible.
  946. if (toCapture == mCapturedView && mDragState == STATE_SETTLING) {
  947. tryCaptureViewForDrag(toCapture, pointerId);
  948. }
  949. final int edgesTouched = mInitialEdgeTouched[pointerId];
  950. if ((edgesTouched & mTrackingEdges) != 0) {
  951. mCallback.onEdgeTouched(edgesTouched & mTrackingEdges, pointerId);
  952. }
  953. break;
  954. }
  955. case MotionEventCompat.ACTION_POINTER_DOWN: {
  956. final int pointerId = MotionEventCompat.getPointerId(ev, actionIndex);
  957. final float x = MotionEventCompat.getX(ev, actionIndex);
  958. final float y = MotionEventCompat.getY(ev, actionIndex);
  959. saveInitialMotion(x, y, pointerId);
  960. // A ViewDragHelper can only manipulate one view at a time.
  961. if (mDragState == STATE_IDLE) {
  962. final int edgesTouched = mInitialEdgeTouched[pointerId];
  963. if ((edgesTouched & mTrackingEdges) != 0) {
  964. mCallback.onEdgeTouched(edgesTouched & mTrackingEdges, pointerId);
  965. }
  966. } else if (mDragState == STATE_SETTLING) {
  967. // Catch a settling view if possible.
  968. final View toCapture = findTopChildUnder((int) x, (int) y);
  969. if (toCapture == mCapturedView) {
  970. tryCaptureViewForDrag(toCapture, pointerId);
  971. }
  972. }
  973. break;
  974. }
  975. case MotionEvent.ACTION_MOVE: {
  976. // First to cross a touch slop over a draggable view wins. Also
  977. // report edge drags.
  978. final int pointerCount = MotionEventCompat.getPointerCount(ev);
  979. for (int i = 0; i < pointerCount; i++) {
  980. final int pointerId = MotionEventCompat.getPointerId(ev, i);
  981. final float x = MotionEventCompat.getX(ev, i);
  982. final float y = MotionEventCompat.getY(ev, i);
  983. final float dx = x - mInitialMotionX[pointerId];
  984. final float dy = y - mInitialMotionY[pointerId];
  985. reportNewEdgeDrags(dx, dy, pointerId);
  986. if (mDragState == STATE_DRAGGING) {
  987. // Callback might have started an edge drag
  988. break;
  989. }
  990. final View toCapture = findTopChildUnder((int) x, (int) y);
  991. if (toCapture != null && checkTouchSlop(toCapture, dx, dy)
  992. && tryCaptureViewForDrag(toCapture, pointerId)) {
  993. break;
  994. }
  995. }
  996. saveLastMotion(ev);
  997. break;
  998. }
  999. case MotionEventCompat.ACTION_POINTER_UP: {
  1000. final int pointerId = MotionEventCompat.getPointerId(ev, actionIndex);
  1001. clearMotionHistory(pointerId);
  1002. break;
  1003. }
  1004. case MotionEvent.ACTION_UP:
  1005. case MotionEvent.ACTION_CANCEL: {
  1006. cancel();
  1007. break;
  1008. }
  1009. }
  1010. return mDragState == STATE_DRAGGING;
  1011. }
  1012. /**
  1013. * Process a touch event received by the parent view. This method will
  1014. * dispatch callback events as needed before returning. The parent view's
  1015. * onTouchEvent implementation should call this.
  1016. *
  1017. * @param ev The touch event received by the parent view
  1018. */
  1019. public void processTouchEvent(MotionEvent ev) {
  1020. final int action = MotionEventCompat.getActionMasked(ev);
  1021. final int actionIndex = MotionEventCompat.getActionIndex(ev);
  1022. if (action == MotionEvent.ACTION_DOWN) {
  1023. // Reset things for a new event stream, just in case we didn't get
  1024. // the whole previous stream.
  1025. cancel();
  1026. }
  1027. if (mVelocityTracker == null) {
  1028. mVelocityTracker = VelocityTracker.obtain();
  1029. }
  1030. mVelocityTracker.addMovement(ev);
  1031. switch (action) {
  1032. case MotionEvent.ACTION_DOWN: {
  1033. final float x = ev.getX();
  1034. final float y = ev.getY();
  1035. final int pointerId = MotionEventCompat.getPointerId(ev, 0);
  1036. final View toCapture = findTopChildUnder((int) x, (int) y);
  1037. saveInitialMotion(x, y, pointerId);
  1038. // Since the parent is already directly processing this touch
  1039. // event,
  1040. // there is no reason to delay for a slop before dragging.
  1041. // Start immediately if possible.
  1042. tryCaptureViewForDrag(toCapture, pointerId);
  1043. final int edgesTouched = mInitialEdgeTouched[pointerId];
  1044. if ((edgesTouched & mTrackingEdges) != 0) {
  1045. mCallback.onEdgeTouched(edgesTouched & mTrackingEdges, pointerId);
  1046. }
  1047. break;
  1048. }
  1049. case MotionEventCompat.ACTION_POINTER_DOWN: {
  1050. final int pointerId = MotionEventCompat.getPointerId(ev, actionIndex);
  1051. final float x = MotionEventCompat.getX(ev, actionIndex);
  1052. final float y = MotionEventCompat.getY(ev, actionIndex);
  1053. saveInitialMotion(x, y, pointerId);
  1054. // A ViewDragHelper can only manipulate one view at a time.
  1055. if (mDragState == STATE_IDLE) {
  1056. // If we're idle we can do anything! Treat it like a normal
  1057. // down event.
  1058. final View toCapture = findTopChildUnder((int) x, (int) y);
  1059. tryCaptureViewForDrag(toCapture, pointerId);
  1060. final int edgesTouched = mInitialEdgeTouched[pointerId];
  1061. if ((edgesTouched & mTrackingEdges) != 0) {
  1062. mCallback.onEdgeTouched(edgesTouched & mTrackingEdges, pointerId);
  1063. }
  1064. } else if (isCapturedViewUnder((int) x, (int) y)) {
  1065. // We're still tracking a captured view. If the same view is
  1066. // under this
  1067. // point, we'll swap to controlling it with this pointer
  1068. // instead.
  1069. // (This will still work if we're "catching" a settling
  1070. // view.)
  1071. tryCaptureViewForDrag(mCapturedView, pointerId);
  1072. }
  1073. break;
  1074. }
  1075. case MotionEvent.ACTION_MOVE: {
  1076. if (mDragState == STATE_DRAGGING) {
  1077. final int index = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
  1078. final float x = MotionEventCompat.getX(ev, index);
  1079. final float y = MotionEventCompat.getY(ev, index);
  1080. final int idx = (int) (x - mLastMotionX[mActivePointerId]);
  1081. final int idy = (int) (y - mLastMotionY[mActivePointerId]);
  1082. dragTo(mCapturedView.getLeft() + idx, mCapturedView.getTop() + idy, idx, idy);
  1083. saveLastMotion(ev);
  1084. } else {
  1085. // Check to see if any pointer is now over a draggable view.
  1086. final int pointerCount = MotionEventCompat.getPointerCount(ev);
  1087. for (int i = 0; i < pointerCount; i++) {
  1088. final int pointerId = MotionEventCompat.getPointerId(ev, i);
  1089. final float x = MotionEventCompat.getX(ev, i);
  1090. final float y = MotionEventCompat.getY(ev, i);
  1091. final float dx = x - mInitialMotionX[pointerId];
  1092. final float dy = y - mInitialMotionY[pointerId];
  1093. reportNewEdgeDrags(dx, dy, pointerId);
  1094. if (mDragState == STATE_DRAGGING) {
  1095. // Callback might have started an edge drag.
  1096. break;
  1097. }
  1098. final View toCapture = findTopChildUnder((int) x, (int) y);
  1099. if (checkTouchSlop(toCapture, dx, dy)
  1100. && tryCaptureViewForDrag(toCapture, pointerId)) {
  1101. break;
  1102. }
  1103. }
  1104. saveLastMotion(ev);
  1105. }
  1106. break;
  1107. }
  1108. case MotionEventCompat.ACTION_POINTER_UP: {
  1109. final int pointerId = MotionEventCompat.getPointerId(ev, actionIndex);
  1110. if (mDragState == STATE_DRAGGING && pointerId == mActivePointerId) {
  1111. // Try to find another pointer that's still holding on to
  1112. // the captured view.
  1113. int newActivePointer = INVALID_POINTER;
  1114. final int pointerCount = MotionEventCompat.getPointerCount(ev);
  1115. for (int i = 0; i < pointerCount; i++) {
  1116. final int id = MotionEventCompat.getPointerId(ev, i);
  1117. if (id == mActivePointerId) {
  1118. // This one's going away, skip.
  1119. continue;
  1120. }
  1121. final float x = MotionEventCompat.getX(ev, i);
  1122. final float y = MotionEventCompat.getY(ev, i);
  1123. if (findTopChildUnder((int) x, (int) y) == mCapturedView
  1124. && tryCaptureViewForDrag(mCapturedView, id)) {
  1125. newActivePointer = mActivePointerId;
  1126. break;
  1127. }
  1128. }
  1129. if (newActivePointer == INVALID_POINTER) {
  1130. // We didn't find another pointer still touching the
  1131. // view, release it.
  1132. releaseViewForPointerUp();
  1133. }
  1134. }
  1135. clearMotionHistory(pointerId);
  1136. break;
  1137. }
  1138. case MotionEvent.ACTION_UP: {
  1139. if (mDragState == STATE_DRAGGING) {
  1140. releaseViewForPointerUp();
  1141. }
  1142. cancel();
  1143. break;
  1144. }
  1145. case MotionEvent.ACTION_CANCEL: {
  1146. if (mDragState == STATE_DRAGGING) {
  1147. dispatchViewReleased(0, 0);
  1148. }
  1149. cancel();
  1150. break;
  1151. }
  1152. }
  1153. }
  1154. private void reportNewEdgeDrags(float dx, float dy, int pointerId) {
  1155. int dragsStarted = 0;
  1156. if (checkNewEdgeDrag(dx, dy, pointerId, EDGE_LEFT)) {
  1157. dragsStarted |= EDGE_LEFT;
  1158. }
  1159. if (checkNewEdgeDrag(dy, dx, pointerId, EDGE_TOP)) {
  1160. dragsStarted |= EDGE_TOP;
  1161. }
  1162. if (checkNewEdgeDrag(dx, dy, pointerId, EDGE_RIGHT)) {
  1163. dragsStarted |= EDGE_RIGHT;
  1164. }
  1165. if (checkNewEdgeDrag(dy, dx, pointerId, EDGE_BOTTOM)) {
  1166. dragsStarted |= EDGE_BOTTOM;
  1167. }
  1168. if (dragsStarted != 0) {
  1169. mEdgeDragsInProgress[pointerId] |= dragsStarted;
  1170. mCallback.onEdgeDragStarted(dragsStarted, pointerId);
  1171. }
  1172. }
  1173. private boolean checkNewEdgeDrag(float delta, float odelta, int pointerId, int edge) {
  1174. final float absDelta = Math.abs(delta);
  1175. final float absODelta = Math.abs(odelta);
  1176. if ((mInitialEdgeTouched[pointerId] & edge) != edge || (mTrackingEdges & edge) == 0
  1177. || (mEdgeDragsLocked[pointerId] & edge) == edge
  1178. || (mEdgeDragsInProgress[pointerId] & edge) == edge
  1179. || (absDelta <= mTouchSlop && absODelta <= mTouchSlop)) {
  1180. return false;
  1181. }
  1182. if (absDelta < absODelta * 0.5f && mCallback.onEdgeLock(edge)) {
  1183. mEdgeDragsLocked[pointerId] |= edge;
  1184. return false;
  1185. }
  1186. return (mEdgeDragsInProgress[pointerId] & edge) == 0 && absDelta > mTouchSlop;
  1187. }
  1188. /**
  1189. * Check if we've crossed a reasonable touch slop for the given child view.
  1190. * If the child cannot be dragged along the horizontal or vertical axis,
  1191. * motion along that axis will not count toward the slop check.
  1192. *
  1193. * @param child Child to check
  1194. * @param dx Motion since initial position along X axis
  1195. * @param dy Motion since initial position along Y axis
  1196. * @return true if the touch slop has been crossed
  1197. */
  1198. private boolean checkTouchSlop(View child, float dx, float dy) {
  1199. if (child == null) {
  1200. return false;
  1201. }
  1202. final boolean checkHorizontal = mCallback.getViewHorizontalDragRange(child) > 0;
  1203. final boolean checkVertical = mCallback.getViewVerticalDragRange(child) > 0;
  1204. if (checkHorizontal && checkVertical) {
  1205. return dx * dx + dy * dy > mTouchSlop * mTouchSlop;
  1206. } else if (checkHorizontal) {
  1207. return Math.abs(dx) > mTouchSlop;
  1208. } else if (checkVertical) {
  1209. return Math.abs(dy) > mTouchSlop;
  1210. }
  1211. return false;
  1212. }
  1213. /**
  1214. * Check if any pointer tracked in the current gesture has crossed the
  1215. * required slop threshold.
  1216. * <p>
  1217. * This depends on internal state populated by
  1218. * {@link #shouldInterceptTouchEvent(android.view.MotionEvent)} or
  1219. * {@link #processTouchEvent(android.view.MotionEvent)}. You should only
  1220. * rely on the results of this method after all currently available touch
  1221. * data has been provided to one of these two methods.
  1222. * </p>
  1223. *
  1224. * @param directions Combination of direction flags, see
  1225. * {@link #DIRECTION_HORIZONTAL}, {@link #DIRECTION_VERTICAL},
  1226. * {@link #DIRECTION_ALL}
  1227. * @return true if the slop threshold has been crossed, false otherwise
  1228. */
  1229. public boolean checkTouchSlop(int directions) {
  1230. final int count = mInitialMotionX.length;
  1231. for (int i = 0; i < count; i++) {
  1232. if (checkTouchSlop(directions, i)) {
  1233. return true;
  1234. }
  1235. }
  1236. return false;
  1237. }
  1238. /**
  1239. * Check if the specified pointer tracked in the current gesture has crossed
  1240. * the required slop threshold.
  1241. * <p>
  1242. * This depends on internal state populated by
  1243. * {@link #shouldInterceptTouchEvent(android.view.MotionEvent)} or
  1244. * {@link #processTouchEvent(android.view.MotionEvent)}. You should only
  1245. * rely on the results of this method after all currently available touch
  1246. * data has been provided to one of these two methods.
  1247. * </p>
  1248. *
  1249. * @param directions Combination of direction flags, see
  1250. * {@link #DIRECTION_HORIZONTAL}, {@link #DIRECTION_VERTICAL},
  1251. * {@link #DIRECTION_ALL}
  1252. * @param pointerId ID of the pointer to slop check as specified by
  1253. * MotionEvent
  1254. * @return true if the slop threshold has been crossed, false otherwise
  1255. */
  1256. public boolean checkTouchSlop(int directions, int pointerId) {
  1257. if (!isPointerDown(pointerId)) {
  1258. return false;
  1259. }
  1260. final boolean checkHorizontal = (directions & DIRECTION_HORIZONTAL) == DIRECTION_HORIZONTAL;
  1261. final boolean checkVertical = (directions & DIRECTION_VERTICAL) == DIRECTION_VERTICAL;
  1262. final float dx = mLastMotionX[pointerId] - mInitialMotionX[pointerId];
  1263. final float dy = mLastMotionY[pointerId] - mInitialMotionY[pointerId];
  1264. if (checkHorizontal && checkVertical) {
  1265. return dx * dx + dy * dy > mTouchSlop * mTouchSlop;
  1266. } else if (checkHorizontal) {
  1267. return Math.abs(dx) > mTouchSlop;
  1268. } else if (checkVertical) {
  1269. return Math.abs(dy) > mTouchSlop;
  1270. }
  1271. return false;
  1272. }
  1273. /**
  1274. * Check if any of the edges specified were initially touched in the
  1275. * currently active gesture. If there is no currently active gesture this
  1276. * method will return false.
  1277. *
  1278. * @param edges Edges to check for an initial edge touch. See
  1279. * {@link #EDGE_LEFT}, {@link #EDGE_TOP}, {@link #EDGE_RIGHT},
  1280. * {@link #EDGE_BOTTOM} and {@link #EDGE_ALL}
  1281. * @return true if any of the edges specified were initially touched in the
  1282. * current gesture
  1283. */
  1284. public boolean isEdgeTouched(int edges) {
  1285. final int count = mInitialEdgeTouched.length;
  1286. for (int i = 0; i < count; i++) {
  1287. if (isEdgeTouched(edges, i)) {
  1288. return true;
  1289. }
  1290. }
  1291. return false;
  1292. }
  1293. /**
  1294. * Check if any of the edges specified were initially touched by the pointer
  1295. * with the specified ID. If there is no currently active gesture or if
  1296. * there is no pointer with the given ID currently down this method will
  1297. * return false.
  1298. *
  1299. * @param edges Edges to check for an initial edge touch. See
  1300. * {@link #EDGE_LEFT}, {@link #EDGE_TOP}, {@link #EDGE_RIGHT},
  1301. * {@link #EDGE_BOTTOM} and {@link #EDGE_ALL}
  1302. * @return true if any of the edges specified were initially touched in the
  1303. * current gesture
  1304. */
  1305. public boolean isEdgeTouched(int edges, int pointerId) {
  1306. return isPointerDown(pointerId) && (mInitialEdgeTouched[pointerId] & edges) != 0;
  1307. }
  1308. private void releaseViewForPointerUp() {
  1309. mVelocityTracker.computeCurrentVelocity(1000, mMaxVelocity);
  1310. final float xvel = clampMag(
  1311. VelocityTrackerCompat.getXVelocity(mVelocityTracker, mActivePointerId),
  1312. mMinVelocity, mMaxVelocity);
  1313. final float yvel = clampMag(
  1314. VelocityTrackerCompat.getYVelocity(mVelocityTracker, mActivePointerId),
  1315. mMinVelocity, mMaxVelocity);
  1316. dispatchViewReleased(xvel, yvel);
  1317. }
  1318. private void dragTo(int left, int top, int dx, int dy) {
  1319. int clampedX = left;
  1320. int clampedY = top;
  1321. final int oldLeft = mCapturedView.getLeft();
  1322. final int oldTop = mCapturedView.getTop();
  1323. if (dx != 0) {
  1324. clampedX = mCallback.clampViewPositionHorizontal(mCapturedView, left, dx);
  1325. mCapturedView.offsetLeftAndRight(clampedX - oldLeft);
  1326. }
  1327. if (dy != 0) {
  1328. clampedY = mCallback.clampViewPositionVertical(mCapturedView, top, dy);
  1329. mCapturedView.offsetTopAndBottom(clampedY - oldTop);
  1330. }
  1331. if (dx != 0 || dy != 0) {
  1332. final int clampedDx = clampedX - oldLeft;
  1333. final int clampedDy = clampedY - oldTop;
  1334. mCallback
  1335. .onViewPositionChanged(mCapturedView, clampedX, clampedY, clampedDx, clampedDy);
  1336. }
  1337. }
  1338. /**
  1339. * Determine if the currently captured view is under the given point in the
  1340. * parent view's coordinate system. If there is no captured view this method
  1341. * will return false.
  1342. *
  1343. * @param x X position to test in the parent's coordinate system
  1344. * @param y Y position to test in the parent's coordinate system
  1345. * @return true if the captured view is under the given point, false
  1346. * otherwise
  1347. */
  1348. public boolean isCapturedViewUnder(int x, int y) {
  1349. return isViewUnder(mCapturedView, x, y);
  1350. }
  1351. /**
  1352. * Determine if the supplied view is under the given point in the parent
  1353. * view's coordinate system.
  1354. *
  1355. * @param view Child view of the parent to hit test
  1356. * @param x X position to test in the parent's coordinate system
  1357. * @param y Y position to test in the parent's coordinate system
  1358. * @return true if the supplied view is under the given point, false
  1359. * otherwise
  1360. */
  1361. public boolean isViewUnder(View view, int x, int y) {
  1362. if (view == null) {
  1363. return false;
  1364. }
  1365. return x >= view.getLeft() && x < view.getRight() && y >= view.getTop()
  1366. && y < view.getBottom();
  1367. }
  1368. /**
  1369. * Find the topmost child under the given point within the parent view's
  1370. * coordinate system. The child order is determined using
  1371. * {@link me.imid.swipebacklayout.lib.ViewDragHelper.Callback#getOrderedChildIndex(int)}
  1372. * .
  1373. *
  1374. * @param x X position to test in the parent's coordinate system
  1375. * @param y Y position to test in the parent's coordinate system
  1376. * @return The topmost child view under (x, y) or null if none found.
  1377. */
  1378. public View findTopChildUnder(int x, int y) {
  1379. final int childCount = mParentView.getChildCount();
  1380. for (int i = childCount - 1; i >= 0; i--) {
  1381. final View child = mParentView.getChildAt(mCallback.getOrderedChildIndex(i));
  1382. if (x >= child.getLeft() && x < child.getRight() && y >= child.getTop()
  1383. && y < child.getBottom()) {
  1384. return child;
  1385. }
  1386. }
  1387. return null;
  1388. }
  1389. private int getEdgeTouched(int x, int y) {
  1390. int result = 0;
  1391. if (x < mParentView.getLeft() + mEdgeSize)
  1392. result = EDGE_LEFT;
  1393. if (y < mParentView.getTop() + mEdgeSize)
  1394. result = EDGE_TOP;
  1395. if (x > mParentView.getRight() - mEdgeSize)
  1396. result = EDGE_RIGHT;
  1397. if (y > mParentView.getBottom() - mEdgeSize)
  1398. result = EDGE_BOTTOM;
  1399. return EDGE_LEFT;
  1400. }
  1401. }