blob: 421571b6b7176efc6c20f100a53e5932885c34ba [file] [log] [blame]
alision7297bdb2013-05-21 11:56:55 -04001package com.savoirfairelinux.sflphone.views;
2
3import android.content.Context;
4import android.content.res.TypedArray;
5import android.graphics.Bitmap;
6import android.graphics.Canvas;
7import android.graphics.Rect;
8import android.os.Handler;
9import android.os.Message;
10import android.os.SystemClock;
11import android.util.AttributeSet;
12import android.util.Log;
13import android.view.MotionEvent;
14import android.view.SoundEffectConstants;
15import android.view.VelocityTracker;
16import android.view.View;
17import android.view.ViewGroup;
18import android.view.accessibility.AccessibilityEvent;
19
20import com.savoirfairelinux.sflphone.R;
21
22/**
23 * SlidingDrawer hides content out of the screen and allows the user to drag a
24 * handle to bring the content on screen. SlidingDrawer can be used vertically
25 * or horizontally.
26 *
27 * A special widget composed of two children views: the handle, that the users
28 * drags, and the content, attached to the handle and dragged with it.
29 *
30 * SlidingDrawer should be used as an overlay inside layouts. This means
31 * SlidingDrawer should only be used inside of a FrameLayout or a RelativeLayout
32 * for instance. The size of the SlidingDrawer defines how much space the
33 * content will occupy once slid out so SlidingDrawer should usually use
34 * match_parent for both its dimensions.
35 *
36 * Inside an XML layout, SlidingDrawer must define the id of the handle and of
37 * the content:
38 *
39 * <pre class="prettyprint">
40 * &lt;SlidingDrawer
41 * android:id="@+id/drawer"
42 * android:layout_width="match_parent"
43 * android:layout_height="match_parent"
44 *
45 * android:handle="@+id/handle"
46 * android:content="@+id/content"&gt;
47 *
48 * &lt;ImageView
49 * android:id="@id/handle"
50 * android:layout_width="88dip"
51 * android:layout_height="44dip" /&gt;
52 *
53 * &lt;GridView
54 * android:id="@id/content"
55 * android:layout_width="match_parent"
56 * android:layout_height="match_parent" /&gt;
57 *
58 * &lt;/SlidingDrawer&gt;
59 * </pre>
60 *
61 * @attr ref android.R.styleable#SlidingDrawer_content
62 * @attr ref android.R.styleable#SlidingDrawer_handle
63 * @attr ref android.R.styleable#SlidingDrawer_topOffset
64 * @attr ref android.R.styleable#SlidingDrawer_bottomOffset
65 * @attr ref android.R.styleable#SlidingDrawer_orientation
66 * @attr ref android.R.styleable#SlidingDrawer_allowSingleTap
67 * @attr ref android.R.styleable#SlidingDrawer_animateOnClick
68 *
69 */
70
71public class CustomSlidingDrawer extends ViewGroup {
72 public static final int ORIENTATION_HORIZONTAL = 0;
73 public static final int ORIENTATION_VERTICAL = 1;
74
75 private static final int TAP_THRESHOLD = 6;
76 private static final float MAXIMUM_TAP_VELOCITY = 100.0f;
77 private static final float MAXIMUM_MINOR_VELOCITY = 150.0f;
78 private static final float MAXIMUM_MAJOR_VELOCITY = 200.0f;
79 private static final float MAXIMUM_ACCELERATION = 2000.0f;
80 private static final int VELOCITY_UNITS = 1000;
81 private static final int MSG_ANIMATE = 1000;
82 private static final int ANIMATION_FRAME_DURATION = 1000 / 60;
83
84 private static final int EXPANDED_FULL_OPEN = -10001;
85 private static final int COLLAPSED_FULL_CLOSED = -10002;
86 private static final String TAG = CustomSlidingDrawer.class.getSimpleName();
87
88 private final int mHandleId;
89 private final int mContentId;
90
91 private View mHandle;
92 private View mTrackHandle;
93 private View mContent;
94
95 private final Rect mFrame = new Rect();
96 private final Rect mInvalidate = new Rect();
97 private boolean mTracking;
98 private boolean mLocked;
99
100 private VelocityTracker mVelocityTracker;
101
102 private boolean mVertical;
103 private boolean mExpanded;
104 private int mBottomOffset;
105 private int mTopOffset;
106 private int mHandleHeight;
107 private int mHandleWidth;
108
109 private OnDrawerOpenListener mOnDrawerOpenListener;
110 private OnDrawerCloseListener mOnDrawerCloseListener;
111 private OnDrawerScrollListener mOnDrawerScrollListener;
112
113 private final Handler mHandler = new SlidingHandler();
114 private float mAnimatedAcceleration;
115 private float mAnimatedVelocity;
116 private float mAnimationPosition;
117 private long mAnimationLastTime;
118 private long mCurrentAnimationTime;
119 private int mTouchDelta;
120 private boolean mAnimating;
121 private boolean mAllowSingleTap;
122 private boolean mAnimateOnClick;
123
124 private final int mTapThreshold;
125 private final int mMaximumTapVelocity;
126 private final int mMaximumMinorVelocity;
127 private final int mMaximumMajorVelocity;
128 private final int mMaximumAcceleration;
129 private final int mVelocityUnits;
130
131 /**
132 * Callback invoked when the drawer is opened.
133 */
134 public static interface OnDrawerOpenListener {
135 /**
136 * Invoked when the drawer becomes fully open.
137 */
138 public void onDrawerOpened();
139 }
140
141 /**
142 * Callback invoked when the drawer is closed.
143 */
144 public static interface OnDrawerCloseListener {
145 /**
146 * Invoked when the drawer becomes fully closed.
147 */
148 public void onDrawerClosed();
149 }
150
151 /**
152 * Callback invoked when the drawer is scrolled.
153 */
154 public static interface OnDrawerScrollListener {
155 /**
156 * Invoked when the user starts dragging/flinging the drawer's handle.
157 */
158 public void onScrollStarted();
159
160 /**
161 * Invoked when the user stops dragging/flinging the drawer's handle.
162 */
163 public void onScrollEnded();
164 }
165
166 /**
167 * Creates a new SlidingDrawer from a specified set of attributes defined in
168 * XML.
169 *
170 * @param context
171 * The application's environment.
172 * @param attrs
173 * The attributes defined in XML.
174 */
175 public CustomSlidingDrawer(Context context, AttributeSet attrs) {
176 this(context, attrs, 0);
177 }
178
179 /**
180 * Creates a new SlidingDrawer from a specified set of attributes defined in
181 * XML.
182 *
183 * @param context
184 * The application's environment.
185 * @param attrs
186 * The attributes defined in XML.
187 * @param defStyle
188 * The style to apply to this widget.
189 */
190 public CustomSlidingDrawer(Context context, AttributeSet attrs, int defStyle) {
191 super(context, attrs, defStyle);
192 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomSlidingDrawer, defStyle, 0);
193
194 int orientation = a.getInt(R.styleable.CustomSlidingDrawer_orientation, ORIENTATION_VERTICAL);
195 mVertical = orientation == ORIENTATION_VERTICAL;
196 mBottomOffset = (int) a.getDimension(R.styleable.CustomSlidingDrawer_bottomOffset, 0.0f);
197 mTopOffset = (int) a.getDimension(R.styleable.CustomSlidingDrawer_topOffset, 0.0f) - 5;
198 mAllowSingleTap = a.getBoolean(R.styleable.CustomSlidingDrawer_allowSingleTap, false);
199 mAnimateOnClick = a.getBoolean(R.styleable.CustomSlidingDrawer_animateOnClick, false);
200
201 int handleId = a.getResourceId(R.styleable.CustomSlidingDrawer_handle, 0);
202 if (handleId == 0) {
203 throw new IllegalArgumentException("The handle attribute is required and must refer " + "to a valid child.");
204 }
205
206 int contentId = a.getResourceId(R.styleable.CustomSlidingDrawer_content, 0);
207 if (contentId == 0) {
208 throw new IllegalArgumentException("The content attribute is required and must refer " + "to a valid child.");
209 }
210
211 if (handleId == contentId) {
212 throw new IllegalArgumentException("The content and handle attributes must refer " + "to different children.");
213 }
214
215 mHandleId = handleId;
216 mContentId = contentId;
217
218 final float density = getResources().getDisplayMetrics().density;
219 mTapThreshold = (int) (TAP_THRESHOLD * density + 0.5f);
220 mMaximumTapVelocity = (int) (MAXIMUM_TAP_VELOCITY * density + 0.5f);
221 mMaximumMinorVelocity = (int) (MAXIMUM_MINOR_VELOCITY * density + 0.5f);
222 mMaximumMajorVelocity = (int) (MAXIMUM_MAJOR_VELOCITY * density + 0.5f);
223 mMaximumAcceleration = (int) (MAXIMUM_ACCELERATION * density + 0.5f);
224 mVelocityUnits = (int) (VELOCITY_UNITS * density + 0.5f);
225
226 a.recycle();
227
228 setAlwaysDrawnWithCacheEnabled(false);
229 }
230
231 @Override
232 protected void onFinishInflate() {
233 mHandle = findViewById(mHandleId);
234 if (mHandle == null) {
235 throw new IllegalArgumentException("The handle attribute is must refer to an" + " existing child.");
236 }
237 mHandle.setOnClickListener(new DrawerToggler());
238
239 mContent = findViewById(mContentId);
240 if (mContent == null) {
241 throw new IllegalArgumentException("The content attribute is must refer to an" + " existing child.");
242 }
243 mContent.setVisibility(View.GONE);
244 }
245
246 @Override
247 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
248 int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
249 int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
250
251 int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
252 int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
253
254 if (widthSpecMode == MeasureSpec.UNSPECIFIED || heightSpecMode == MeasureSpec.UNSPECIFIED) {
255 throw new RuntimeException("SlidingDrawer cannot have UNSPECIFIED dimensions");
256 }
257
258 final View handle = mHandle;
259 measureChild(handle, widthMeasureSpec, heightMeasureSpec);
260
261 if (mVertical) {
262 int height = heightSpecSize - handle.getMeasuredHeight() - mTopOffset;
263 mContent.measure(MeasureSpec.makeMeasureSpec(widthSpecSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
264 } else {
265 int width = widthSpecSize - handle.getMeasuredWidth() - mTopOffset;
266 mContent.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(heightSpecSize, MeasureSpec.EXACTLY));
267 }
268
269 setMeasuredDimension(widthSpecSize, heightSpecSize);
270 }
271
272 @Override
273 protected void dispatchDraw(Canvas canvas) {
274 final long drawingTime = getDrawingTime();
275 final View handle = mHandle;
276 final boolean isVertical = mVertical;
277
278 drawChild(canvas, handle, drawingTime);
279
280 if (mTracking || mAnimating) {
281 final Bitmap cache = mContent.getDrawingCache();
282 if (cache != null) {
283 if (isVertical) {
284 canvas.drawBitmap(cache, 0, handle.getBottom(), null);
285 } else {
286 canvas.drawBitmap(cache, handle.getRight(), 0, null);
287 }
288 } else {
289 canvas.save();
290 canvas.translate(isVertical ? 0 : handle.getLeft() - mTopOffset, isVertical ? handle.getTop() - mTopOffset : 0);
291 drawChild(canvas, mContent, drawingTime);
292 canvas.restore();
293 }
294 } else if (mExpanded) {
295 drawChild(canvas, mContent, drawingTime);
296 }
297 }
298
299 @Override
300 protected void onLayout(boolean changed, int l, int t, int r, int b) {
301 if (mTracking) {
302 return;
303 }
304
305 final int width = r - l;
306 final int height = b - t;
307
308 final View handle = mHandle;
309
310 int childWidth = handle.getMeasuredWidth();
311 int childHeight = handle.getMeasuredHeight();
312
313 int childLeft;
314 int childTop;
315
316 final View content = mContent;
317
318 if (mVertical) {
319 childLeft = (width - childWidth) / 2;
320 childTop = mExpanded ? mTopOffset : height - childHeight + mBottomOffset;
321
322 content.layout(0, mTopOffset + childHeight, content.getMeasuredWidth(), mTopOffset + childHeight + content.getMeasuredHeight());
323 } else {
324 childLeft = mExpanded ? mTopOffset : width - childWidth + mBottomOffset;
325 childTop = (height - childHeight) / 2;
326
327 content.layout(mTopOffset + childWidth, 0, mTopOffset + childWidth + content.getMeasuredWidth(), content.getMeasuredHeight());
328 }
329
330 handle.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight);
331 mHandleHeight = handle.getHeight();
332 mHandleWidth = handle.getWidth();
333 }
334
335 @Override
336 public boolean onInterceptTouchEvent(MotionEvent event) {
337
338 Log.i(TAG, "onInterceptTouchEvent");
339 if (mLocked) {
340 Log.i(TAG, "Locked");
341 return false;
342 }
343
344 final int action = event.getAction();
345
346 float x = event.getX();
347 float y = event.getY();
348
349 final Rect frame = mFrame;
350 final View handle = mHandle;
351
352 // New code
353 View trackHandle = mTrackHandle;
354 // set the rect frame to the mTrackHandle view borders instead of the
355 // hole handle view
356
357 // getParent() => The right and left are valid, but we need to get the
358 // parent top and bottom to have absolute values (in screen)
359 frame.set(trackHandle.getLeft(), ((ViewGroup) trackHandle.getParent()).getTop(), trackHandle.getRight(), ((ViewGroup) trackHandle.getParent()).getBottom());
360
361// handle.getHitRect(frame);
362 if (!mTracking && !frame.contains((int) x, (int) y)) {
363 Log.i(TAG, "not tracking and not in frame");
364 return false;
365 }
366
367 if (action == MotionEvent.ACTION_DOWN) {
368 mTracking = true;
369 Log.i(TAG, "action down");
370 handle.setPressed(true);
371 // Must be called before prepareTracking()
372 prepareContent();
373
374 // Must be called after prepareContent()
375 if (mOnDrawerScrollListener != null) {
376 mOnDrawerScrollListener.onScrollStarted();
377 }
378
379 if (mVertical) {
380 final int top = mHandle.getTop();
381 mTouchDelta = (int) y - top;
382 prepareTracking(top);
383 } else {
384 final int left = mHandle.getLeft();
385 mTouchDelta = (int) x - left;
386 prepareTracking(left);
387 }
388 mVelocityTracker.addMovement(event);
389 }
390
391 return true;
392 }
393
394 @Override
395 public boolean onTouchEvent(MotionEvent event) {
396 if (mLocked) {
397 return true;
398 }
399
400 if (mTracking) {
401 mVelocityTracker.addMovement(event);
402 final int action = event.getAction();
403 switch (action) {
404 case MotionEvent.ACTION_MOVE:
405 moveHandle((int) (mVertical ? event.getY() : event.getX()) - mTouchDelta);
406 break;
407 case MotionEvent.ACTION_UP:
408 case MotionEvent.ACTION_CANCEL: {
409 final VelocityTracker velocityTracker = mVelocityTracker;
410 velocityTracker.computeCurrentVelocity(mVelocityUnits);
411
412 float yVelocity = velocityTracker.getYVelocity();
413 float xVelocity = velocityTracker.getXVelocity();
414 boolean negative;
415
416 final boolean vertical = mVertical;
417 if (vertical) {
418 negative = yVelocity < 0;
419 if (xVelocity < 0) {
420 xVelocity = -xVelocity;
421 }
422 if (xVelocity > mMaximumMinorVelocity) {
423 xVelocity = mMaximumMinorVelocity;
424 }
425 } else {
426 negative = xVelocity < 0;
427 if (yVelocity < 0) {
428 yVelocity = -yVelocity;
429 }
430 if (yVelocity > mMaximumMinorVelocity) {
431 yVelocity = mMaximumMinorVelocity;
432 }
433 }
434
435 float velocity = (float) Math.hypot(xVelocity, yVelocity);
436 if (negative) {
437 velocity = -velocity;
438 }
439
440 final int top = mHandle.getTop();
441 final int left = mHandle.getLeft();
442
443 if (Math.abs(velocity) < mMaximumTapVelocity) {
444 if (vertical ? (mExpanded && top < mTapThreshold + mTopOffset) || (!mExpanded && top > mBottomOffset + getBottom() - getTop() - mHandleHeight - mTapThreshold) : (mExpanded && left < mTapThreshold + mTopOffset)
445 || (!mExpanded && left > mBottomOffset + getRight() - getLeft() - mHandleWidth - mTapThreshold)) {
446
447 if (mAllowSingleTap) {
448 playSoundEffect(SoundEffectConstants.CLICK);
449
450 if (mExpanded) {
451 animateClose(vertical ? top : left);
452 } else {
453 animateOpen(vertical ? top : left);
454 }
455 } else {
456 performFling(vertical ? top : left, velocity, false);
457 }
458
459 } else {
460 performFling(vertical ? top : left, velocity, false);
461 }
462 } else {
463 performFling(vertical ? top : left, velocity, false);
464 }
465 }
466 break;
467 }
468 }
469
470 return mTracking || mAnimating || super.onTouchEvent(event);
471 }
472
473 private void animateClose(int position) {
474 prepareTracking(position);
475 performFling(position, mMaximumAcceleration, true);
476 }
477
478 private void animateOpen(int position) {
479 prepareTracking(position);
480 performFling(position, -mMaximumAcceleration, true);
481 }
482
483 private void performFling(int position, float velocity, boolean always) {
484 mAnimationPosition = position;
485 mAnimatedVelocity = velocity;
486
487 if (mExpanded) {
488 if (always || (velocity > mMaximumMajorVelocity || (position > mTopOffset + (mVertical ? mHandleHeight : mHandleWidth) && velocity > -mMaximumMajorVelocity))) {
489 // We are expanded, but they didn't move sufficiently to cause
490 // us to retract. Animate back to the expanded position.
491 mAnimatedAcceleration = mMaximumAcceleration;
492 if (velocity < 0) {
493 mAnimatedVelocity = 0;
494 }
495 } else {
496 // We are expanded and are now going to animate away.
497 mAnimatedAcceleration = -mMaximumAcceleration;
498 if (velocity > 0) {
499 mAnimatedVelocity = 0;
500 }
501 }
502 } else {
503 if (!always && (velocity > mMaximumMajorVelocity || (position > (mVertical ? getHeight() : getWidth()) / 2 && velocity > -mMaximumMajorVelocity))) {
504 // We are collapsed, and they moved enough to allow us to
505 // expand.
506 mAnimatedAcceleration = mMaximumAcceleration;
507 if (velocity < 0) {
508 mAnimatedVelocity = 0;
509 }
510 } else {
511 // We are collapsed, but they didn't move sufficiently to cause
512 // us to retract. Animate back to the collapsed position.
513 mAnimatedAcceleration = -mMaximumAcceleration;
514 if (velocity > 0) {
515 mAnimatedVelocity = 0;
516 }
517 }
518 }
519
520 long now = SystemClock.uptimeMillis();
521 mAnimationLastTime = now;
522 mCurrentAnimationTime = now + ANIMATION_FRAME_DURATION;
523 mAnimating = true;
524 mHandler.removeMessages(MSG_ANIMATE);
525 mHandler.sendMessageAtTime(mHandler.obtainMessage(MSG_ANIMATE), mCurrentAnimationTime);
526 stopTracking();
527 }
528
529 private void prepareTracking(int position) {
530 mTracking = true;
531 mVelocityTracker = VelocityTracker.obtain();
532 boolean opening = !mExpanded;
533 if (opening) {
534 mAnimatedAcceleration = mMaximumAcceleration;
535 mAnimatedVelocity = mMaximumMajorVelocity;
536 mAnimationPosition = mBottomOffset + (mVertical ? getHeight() - mHandleHeight : getWidth() - mHandleWidth);
537 moveHandle((int) mAnimationPosition);
538 mAnimating = true;
539 mHandler.removeMessages(MSG_ANIMATE);
540 long now = SystemClock.uptimeMillis();
541 mAnimationLastTime = now;
542 mCurrentAnimationTime = now + ANIMATION_FRAME_DURATION;
543 mAnimating = true;
544 } else {
545 if (mAnimating) {
546 mAnimating = false;
547 mHandler.removeMessages(MSG_ANIMATE);
548 }
549 moveHandle(position);
550 }
551 }
552
553 private void moveHandle(int position) {
554 final View handle = mHandle;
555
556 if (mVertical) {
557 if (position == EXPANDED_FULL_OPEN) {
558 handle.offsetTopAndBottom(mTopOffset - handle.getTop());
559 invalidate();
560 } else if (position == COLLAPSED_FULL_CLOSED) {
561 handle.offsetTopAndBottom(mBottomOffset + getBottom() - getTop() - mHandleHeight - handle.getTop());
562 invalidate();
563 } else {
564 final int top = handle.getTop();
565 int deltaY = position - top;
566 if (position < mTopOffset) {
567 deltaY = mTopOffset - top;
568 } else if (deltaY > mBottomOffset + getBottom() - getTop() - mHandleHeight - top) {
569 deltaY = mBottomOffset + getBottom() - getTop() - mHandleHeight - top;
570 }
571 handle.offsetTopAndBottom(deltaY);
572
573 final Rect frame = mFrame;
574 final Rect region = mInvalidate;
575
576 handle.getHitRect(frame);
577 region.set(frame);
578
579 region.union(frame.left, frame.top - deltaY, frame.right, frame.bottom - deltaY);
580 region.union(0, frame.bottom - deltaY, getWidth(), frame.bottom - deltaY + mContent.getHeight());
581
582 invalidate(region);
583 }
584 } else {
585 if (position == EXPANDED_FULL_OPEN) {
586 handle.offsetLeftAndRight(mTopOffset - handle.getLeft());
587 invalidate();
588 } else if (position == COLLAPSED_FULL_CLOSED) {
589 handle.offsetLeftAndRight(mBottomOffset + getRight() - getLeft() - mHandleWidth - handle.getLeft());
590 invalidate();
591 } else {
592 final int left = handle.getLeft();
593 int deltaX = position - left;
594 if (position < mTopOffset) {
595 deltaX = mTopOffset - left;
596 } else if (deltaX > mBottomOffset + getRight() - getLeft() - mHandleWidth - left) {
597 deltaX = mBottomOffset + getRight() - getLeft() - mHandleWidth - left;
598 }
599 handle.offsetLeftAndRight(deltaX);
600
601 final Rect frame = mFrame;
602 final Rect region = mInvalidate;
603
604 handle.getHitRect(frame);
605 region.set(frame);
606
607 region.union(frame.left - deltaX, frame.top, frame.right - deltaX, frame.bottom);
608 region.union(frame.right - deltaX, 0, frame.right - deltaX + mContent.getWidth(), getHeight());
609
610 invalidate(region);
611 }
612 }
613 }
614
615 private void prepareContent() {
616 if (mAnimating) {
617 return;
618 }
619
620 // Something changed in the content, we need to honor the layout request
621 // before creating the cached bitmap
622 final View content = mContent;
623 if (content.isLayoutRequested()) {
624 if (mVertical) {
625 final int childHeight = mHandleHeight;
626 int height = getBottom() - getTop() - childHeight - mTopOffset;
627 content.measure(MeasureSpec.makeMeasureSpec(getRight() - getLeft(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
628 content.layout(0, mTopOffset + childHeight, content.getMeasuredWidth(), mTopOffset + childHeight + content.getMeasuredHeight());
629 } else {
630 final int childWidth = mHandle.getWidth();
631 int width = getRight() - getLeft() - childWidth - mTopOffset;
632 content.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(getBottom() - getTop(), MeasureSpec.EXACTLY));
633 content.layout(childWidth + mTopOffset, 0, mTopOffset + childWidth + content.getMeasuredWidth(), content.getMeasuredHeight());
634 }
635 }
636 // Try only once... we should really loop but it's not a big deal
637 // if the draw was cancelled, it will only be temporary anyway
638 content.getViewTreeObserver().dispatchOnPreDraw();
639 // if (!content.isHardwareAccelerated()) content.buildDrawingCache();
640
641 content.setVisibility(View.GONE);
642 }
643
644 private void stopTracking() {
645 mHandle.setPressed(false);
646 mTracking = false;
647
648 if (mOnDrawerScrollListener != null) {
649 mOnDrawerScrollListener.onScrollEnded();
650 }
651
652 if (mVelocityTracker != null) {
653 mVelocityTracker.recycle();
654 mVelocityTracker = null;
655 }
656 }
657
658 private void doAnimation() {
659 if (mAnimating) {
660 incrementAnimation();
661 if (mAnimationPosition >= mBottomOffset + (mVertical ? getHeight() : getWidth()) - 1) {
662 mAnimating = false;
663 closeDrawer();
664 } else if (mAnimationPosition < mTopOffset) {
665 mAnimating = false;
666 openDrawer();
667 } else {
668 moveHandle((int) mAnimationPosition);
669 mCurrentAnimationTime += ANIMATION_FRAME_DURATION;
670 mHandler.sendMessageAtTime(mHandler.obtainMessage(MSG_ANIMATE), mCurrentAnimationTime);
671 }
672 }
673 }
674
675 private void incrementAnimation() {
676 long now = SystemClock.uptimeMillis();
677 float t = (now - mAnimationLastTime) / 1000.0f; // ms -> s
678 final float position = mAnimationPosition;
679 final float v = mAnimatedVelocity; // px/s
680 final float a = mAnimatedAcceleration; // px/s/s
681 mAnimationPosition = position + (v * t) + (0.5f * a * t * t); // px
682 mAnimatedVelocity = v + (a * t); // px/s
683 mAnimationLastTime = now; // ms
684 }
685
686 /**
687 * Toggles the drawer open and close. Takes effect immediately.
688 *
689 * @see #open()
690 * @see #close()
691 * @see #animateClose()
692 * @see #animateOpen()
693 * @see #animateToggle()
694 */
695 public void toggle() {
696 if (!mExpanded) {
697 openDrawer();
698 } else {
699 closeDrawer();
700 }
701 invalidate();
702 requestLayout();
703 }
704
705 /**
706 * Toggles the drawer open and close with an animation.
707 *
708 * @see #open()
709 * @see #close()
710 * @see #animateClose()
711 * @see #animateOpen()
712 * @see #toggle()
713 */
714 public void animateToggle() {
715 if (!mExpanded) {
716 animateOpen();
717 } else {
718 animateClose();
719 }
720 }
721
722 /**
723 * Opens the drawer immediately.
724 *
725 * @see #toggle()
726 * @see #close()
727 * @see #animateOpen()
728 */
729 public void open() {
730 openDrawer();
731 invalidate();
732 requestLayout();
733
734 sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
735 }
736
737 /**
738 * Closes the drawer immediately.
739 *
740 * @see #toggle()
741 * @see #open()
742 * @see #animateClose()
743 */
744 public void close() {
745 closeDrawer();
746 invalidate();
747 requestLayout();
748 }
749
750 /**
751 * Closes the drawer with an animation.
752 *
753 * @see #close()
754 * @see #open()
755 * @see #animateOpen()
756 * @see #animateToggle()
757 * @see #toggle()
758 */
759 public void animateClose() {
760 prepareContent();
761 final OnDrawerScrollListener scrollListener = mOnDrawerScrollListener;
762 if (scrollListener != null) {
763 scrollListener.onScrollStarted();
764 }
765 animateClose(mVertical ? mHandle.getTop() : mHandle.getLeft());
766
767 if (scrollListener != null) {
768 scrollListener.onScrollEnded();
769 }
770 }
771
772 /**
773 * Opens the drawer with an animation.
774 *
775 * @see #close()
776 * @see #open()
777 * @see #animateClose()
778 * @see #animateToggle()
779 * @see #toggle()
780 */
781 public void animateOpen() {
782 prepareContent();
783 final OnDrawerScrollListener scrollListener = mOnDrawerScrollListener;
784 if (scrollListener != null) {
785 scrollListener.onScrollStarted();
786 }
787 animateOpen(mVertical ? mHandle.getTop() : mHandle.getLeft());
788
789 sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
790
791 if (scrollListener != null) {
792 scrollListener.onScrollEnded();
793 }
794 }
795
796 // @Override
797 // public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
798 // super.onInitializeAccessibilityEvent(event);
799 // event.setClassName(SlidingDrawer.class.getName());
800 // }
801
802 // @Override
803 // public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info)
804 // {
805 // super.onInitializeAccessibilityNodeInfo(info);
806 // info.setClassName(SlidingDrawer.class.getName());
807 // }
808
809 private void closeDrawer() {
810 moveHandle(COLLAPSED_FULL_CLOSED);
811 mContent.setVisibility(View.GONE);
812 mContent.destroyDrawingCache();
813
814 if (!mExpanded) {
815 return;
816 }
817
818 mExpanded = false;
819 if (mOnDrawerCloseListener != null) {
820 mOnDrawerCloseListener.onDrawerClosed();
821 }
822 }
823
824 private void openDrawer() {
825 moveHandle(EXPANDED_FULL_OPEN);
826 mContent.setVisibility(View.VISIBLE);
827
828 if (mExpanded) {
829 return;
830 }
831
832 mExpanded = true;
833
834 if (mOnDrawerOpenListener != null) {
835 mOnDrawerOpenListener.onDrawerOpened();
836 }
837 }
838
839 /**
840 * Sets the listener that receives a notification when the drawer becomes
841 * open.
842 *
843 * @param onDrawerOpenListener
844 * The listener to be notified when the drawer is opened.
845 */
846 public void setOnDrawerOpenListener(OnDrawerOpenListener onDrawerOpenListener) {
847 mOnDrawerOpenListener = onDrawerOpenListener;
848 }
849
850 /**
851 * Sets the listener that receives a notification when the drawer becomes
852 * close.
853 *
854 * @param onDrawerCloseListener
855 * The listener to be notified when the drawer is closed.
856 */
857 public void setOnDrawerCloseListener(OnDrawerCloseListener onDrawerCloseListener) {
858 mOnDrawerCloseListener = onDrawerCloseListener;
859 }
860
861 /**
862 * Sets the listener that receives a notification when the drawer starts or
863 * ends a scroll. A fling is considered as a scroll. A fling will also
864 * trigger a drawer opened or drawer closed event.
865 *
866 * @param onDrawerScrollListener
867 * The listener to be notified when scrolling starts or stops.
868 */
869 public void setOnDrawerScrollListener(OnDrawerScrollListener onDrawerScrollListener) {
870 mOnDrawerScrollListener = onDrawerScrollListener;
871 }
872
873 /**
874 * Returns the handle of the drawer.
875 *
876 * @return The View reprenseting the handle of the drawer, identified by the
877 * "handle" id in XML.
878 */
879 public View getHandle() {
880 return mHandle;
881 }
882
883 /**
884 * Returns the content of the drawer.
885 *
886 * @return The View reprenseting the content of the drawer, identified by
887 * the "content" id in XML.
888 */
889 public View getContent() {
890 return mContent;
891 }
892
893 /**
894 * Unlocks the SlidingDrawer so that touch events are processed.
895 *
896 * @see #lock()
897 */
898 public void unlock() {
899 mLocked = false;
900 }
901
902 /**
903 * Locks the SlidingDrawer so that touch events are ignores.
904 *
905 * @see #unlock()
906 */
907 public void lock() {
908 mLocked = true;
909 }
910
911 /**
912 * Indicates whether the drawer is currently fully opened.
913 *
914 * @return True if the drawer is opened, false otherwise.
915 */
916 public boolean isOpened() {
917 return mExpanded;
918 }
919
920 /**
921 * Indicates whether the drawer is scrolling or flinging.
922 *
923 * @return True if the drawer is scroller or flinging, false otherwise.
924 */
925 public boolean isMoving() {
926 return mTracking || mAnimating;
927 }
928
929 private class DrawerToggler implements OnClickListener {
930 public void onClick(View v) {
931 if (mLocked) {
932 return;
933 }
934 // mAllowSingleTap isn't relevant here; you're *always*
935 // allowed to open/close the drawer by clicking with the
936 // trackball.
937
938 if (mAnimateOnClick) {
939 animateToggle();
940 } else {
941 toggle();
942 }
943 }
944 }
945
946 public void setmTrackHandle(View mTrackHandle) {
947 this.mTrackHandle = mTrackHandle;
948 }
949
950 private class SlidingHandler extends Handler {
951 public void handleMessage(Message m) {
952 switch (m.what) {
953 case MSG_ANIMATE:
954 doAnimation();
955 break;
956 }
957 }
958 }
959}