SlidingPaneLayout.java revision 89e17886e6149bddfdb08a242c9e88889596419c
1/* 2 * Copyright (C) 2012 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.support.v4.widget; 18 19import android.content.Context; 20import android.content.res.TypedArray; 21import android.graphics.Bitmap; 22import android.graphics.Canvas; 23import android.graphics.Paint; 24import android.graphics.PorterDuff; 25import android.graphics.PorterDuffColorFilter; 26import android.graphics.Rect; 27import android.graphics.drawable.Drawable; 28import android.os.Build; 29import android.os.Parcel; 30import android.os.Parcelable; 31import android.support.v4.view.MotionEventCompat; 32import android.support.v4.view.ViewCompat; 33import android.util.AttributeSet; 34import android.util.Log; 35import android.view.MotionEvent; 36import android.view.View; 37import android.view.ViewConfiguration; 38import android.view.ViewGroup; 39 40import java.lang.reflect.Field; 41import java.lang.reflect.Method; 42 43/** 44 * SlidingPaneLayout provides a horizontal, multi-pane layout for use at the top level 45 * of a UI. A left (or first) pane is treated as a content list or browser, subordinate to a 46 * primary detail view for displaying content. 47 * 48 * <p>Child views may overlap if their combined width exceeds the available width 49 * in the SlidingPaneLayout. When this occurs the user may slide the topmost view out of the way 50 * by dragging it, or by navigating in the direction of the overlapped view using a keyboard. 51 * If the content of the dragged child view is itself horizontally scrollable, the user may 52 * grab it by the very edge.</p> 53 * 54 * <p>Thanks to this sliding behavior, SlidingPaneLayout may be suitable for creating layouts 55 * that can smoothly adapt across many different screen sizes, expanding out fully on larger 56 * screens and collapsing on smaller screens.</p> 57 * 58 * <p>SlidingPaneLayout is distinct from a navigation drawer as described in the design 59 * guide and should not be used in the same scenarios. SlidingPaneLayout should be thought 60 * of only as a way to allow a two-pane layout normally used on larger screens to adapt to smaller 61 * screens in a natural way. The interaction patterns expressed by SlidingPaneLayout imply 62 * a physicality and direct information hierarchy between panes that does not necessarily exist 63 * in a scenario where a navigation drawer should be used instead.</p> 64 * 65 * <p>Appropriate uses of SlidingPaneLayout include pairings of panes such as a contact list and 66 * subordinate interactions with those contacts, or an email thread list with the content pane 67 * displaying the contents of the selected thread. Inappropriate uses of SlidingPaneLayout include 68 * switching between disparate functions of your app, such as jumping from a social stream view 69 * to a view of your personal profile - cases such as this should use the navigation drawer 70 * pattern instead. ({@link DrawerLayout DrawerLayout} implements this pattern.)</p> 71 * 72 * <p>Like {@link android.widget.LinearLayout LinearLayout}, SlidingPaneLayout supports 73 * the use of the layout parameter <code>layout_weight</code> on child views to determine 74 * how to divide leftover space after measurement is complete. It is only relevant for width. 75 * When views do not overlap weight behaves as it does in a LinearLayout.</p> 76 * 77 * <p>When views do overlap, weight on a slideable pane indicates that the pane should be 78 * sized to fill all available space in the closed state. Weight on a pane that becomes covered 79 * indicates that the pane should be sized to fill all available space except a small minimum strip 80 * that the user may use to grab the slideable view and pull it back over into a closed state.</p> 81 * 82 * <p>Experimental. This class may be removed.</p> 83 */ 84public class SlidingPaneLayout extends ViewGroup { 85 private static final String TAG = "SlidingPaneLayout"; 86 87 /** 88 * Default size of the overhang for a pane in the open state. 89 * At least this much of a sliding pane will remain visible. 90 * This indicates that there is more content available and provides 91 * a "physical" edge to grab to pull it closed. 92 */ 93 private static final int DEFAULT_OVERHANG_SIZE = 32; // dp; 94 95 /** 96 * If no fade color is given by default it will fade to 80% gray. 97 */ 98 private static final int DEFAULT_FADE_COLOR = 0xcccccccc; 99 100 /** 101 * The fade color used for the sliding panel. 0 = no fading. 102 */ 103 private int mSliderFadeColor = DEFAULT_FADE_COLOR; 104 105 /** 106 * The fade color used for the panel covered by the slider. 0 = no fading. 107 */ 108 private int mCoveredFadeColor; 109 110 /** 111 * Drawable used to draw the shadow between panes. 112 */ 113 private Drawable mShadowDrawable; 114 115 /** 116 * The size of the overhang in pixels. 117 * This is the minimum section of the sliding panel that will 118 * be visible in the open state to allow for a closing drag. 119 */ 120 private final int mOverhangSize; 121 122 /** 123 * True if a panel can slide with the current measurements 124 */ 125 private boolean mCanSlide; 126 127 /** 128 * The child view that can slide, if any. 129 */ 130 private View mSlideableView; 131 132 /** 133 * How far the panel is offset from its closed position. 134 * range [0, 1] where 0 = closed, 1 = open. 135 */ 136 private float mSlideOffset; 137 138 /** 139 * How far the non-sliding panel is parallaxed from its usual position when open. 140 * range [0, 1] 141 */ 142 private float mParallaxOffset; 143 144 /** 145 * How far in pixels the slideable panel may move. 146 */ 147 private int mSlideRange; 148 149 /** 150 * A panel view is locked into internal scrolling or another condition that 151 * is preventing a drag. 152 */ 153 private boolean mIsUnableToDrag; 154 155 /** 156 * Distance in pixels to parallax the fixed pane by when fully closed 157 */ 158 private int mParallaxBy; 159 160 private float mInitialMotionX; 161 private float mInitialMotionY; 162 163 private PanelSlideListener mPanelSlideListener; 164 165 private final ViewDragHelper mDragHelper; 166 167 /** 168 * Stores whether or not the pane was open the last time it was slideable. 169 * If open/close operations are invoked this state is modified. Used by 170 * instance state save/restore. 171 */ 172 private boolean mPreservedOpenState; 173 private boolean mFirstLayout = true; 174 175 private final Rect mTmpRect = new Rect(); 176 177 static final SlidingPanelLayoutImpl IMPL; 178 179 static { 180 final int deviceVersion = Build.VERSION.SDK_INT; 181 if (deviceVersion >= 17) { 182 IMPL = new SlidingPanelLayoutImplJBMR1(); 183 } else if (deviceVersion >= 16) { 184 IMPL = new SlidingPanelLayoutImplJB(); 185 } else { 186 IMPL = new SlidingPanelLayoutImplBase(); 187 } 188 } 189 190 /** 191 * Listener for monitoring events about sliding panes. 192 */ 193 public interface PanelSlideListener { 194 /** 195 * Called when a sliding pane's position changes. 196 * @param panel The child view that was moved 197 * @param slideOffset The new offset of this sliding pane within its range, from 0-1 198 */ 199 public void onPanelSlide(View panel, float slideOffset); 200 /** 201 * Called when a sliding pane becomes slid completely open. The pane may or may not 202 * be interactive at this point depending on how much of the pane is visible. 203 * @param panel The child view that was slid to an open position, revealing other panes 204 */ 205 public void onPanelOpened(View panel); 206 207 /** 208 * Called when a sliding pane becomes slid completely closed. The pane is now guaranteed 209 * to be interactive. It may now obscure other views in the layout. 210 * @param panel The child view that was slid to a closed position 211 */ 212 public void onPanelClosed(View panel); 213 } 214 215 /** 216 * No-op stubs for {@link PanelSlideListener}. If you only want to implement a subset 217 * of the listener methods you can extend this instead of implement the full interface. 218 */ 219 public static class SimplePanelSlideListener implements PanelSlideListener { 220 @Override 221 public void onPanelSlide(View panel, float slideOffset) { 222 } 223 @Override 224 public void onPanelOpened(View panel) { 225 } 226 @Override 227 public void onPanelClosed(View panel) { 228 } 229 } 230 231 public SlidingPaneLayout(Context context) { 232 this(context, null); 233 } 234 235 public SlidingPaneLayout(Context context, AttributeSet attrs) { 236 this(context, attrs, 0); 237 } 238 239 public SlidingPaneLayout(Context context, AttributeSet attrs, int defStyle) { 240 super(context, attrs, defStyle); 241 242 final float density = context.getResources().getDisplayMetrics().density; 243 mOverhangSize = (int) (DEFAULT_OVERHANG_SIZE * density + 0.5f); 244 245 final ViewConfiguration viewConfig = ViewConfiguration.get(context); 246 247 setWillNotDraw(false); 248 249 mDragHelper = ViewDragHelper.create(this, 0.5f, new DragHelperCallback()); 250 mDragHelper.setEdgeTrackingEnabled(ViewDragHelper.EDGE_LEFT); 251 } 252 253 /** 254 * Set a distance to parallax the lower pane by when the upper pane is in its 255 * fully closed state. The lower pane will scroll between this position and 256 * its fully open state. 257 * 258 * @param parallaxBy Distance to parallax by in pixels 259 */ 260 public void setParallaxDistance(int parallaxBy) { 261 mParallaxBy = parallaxBy; 262 requestLayout(); 263 } 264 265 /** 266 * @return The distance the lower pane will parallax by when the upper pane is fully closed. 267 * 268 * @see #setParallaxDistance(int) 269 */ 270 public int getParallaxDistance() { 271 return mParallaxBy; 272 } 273 274 /** 275 * Set the color used to fade the sliding pane out when it is slid most of the way offscreen. 276 * 277 * @param color An ARGB-packed color value 278 */ 279 public void setSliderFadeColor(int color) { 280 mSliderFadeColor = color; 281 } 282 283 /** 284 * @return The ARGB-packed color value used to fade the sliding pane 285 */ 286 public int getSliderFadeColor() { 287 return mSliderFadeColor; 288 } 289 290 /** 291 * Set the color used to fade the pane covered by the sliding pane out when the pane 292 * will become fully covered in the closed state. 293 * 294 * @param color An ARGB-packed color value 295 */ 296 public void setCoveredFadeColor(int color) { 297 mCoveredFadeColor = color; 298 } 299 300 /** 301 * @return The ARGB-packed color value used to fade the fixed pane 302 */ 303 public int getCoveredFadeColor() { 304 return mCoveredFadeColor; 305 } 306 307 public void setPanelSlideListener(PanelSlideListener listener) { 308 mPanelSlideListener = listener; 309 } 310 311 void dispatchOnPanelSlide(View panel) { 312 if (mPanelSlideListener != null) { 313 mPanelSlideListener.onPanelSlide(panel, mSlideOffset); 314 } 315 } 316 317 void dispatchOnPanelOpened(View panel) { 318 if (mPanelSlideListener != null) { 319 mPanelSlideListener.onPanelOpened(panel); 320 } 321 } 322 323 void dispatchOnPanelClosed(View panel) { 324 if (mPanelSlideListener != null) { 325 mPanelSlideListener.onPanelClosed(panel); 326 } 327 } 328 329 @Override 330 protected void onAttachedToWindow() { 331 super.onAttachedToWindow(); 332 mFirstLayout = true; 333 } 334 335 @Override 336 protected void onDetachedFromWindow() { 337 super.onDetachedFromWindow(); 338 mFirstLayout = true; 339 } 340 341 @Override 342 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 343 final int widthMode = MeasureSpec.getMode(widthMeasureSpec); 344 final int widthSize = MeasureSpec.getSize(widthMeasureSpec); 345 final int heightMode = MeasureSpec.getMode(heightMeasureSpec); 346 final int heightSize = MeasureSpec.getSize(heightMeasureSpec); 347 348 if (widthMode != MeasureSpec.EXACTLY) { 349 throw new IllegalStateException("Width must have an exact value or MATCH_PARENT"); 350 } else if (heightMode == MeasureSpec.UNSPECIFIED) { 351 throw new IllegalStateException("Height must not be UNSPECIFIED"); 352 } 353 354 int layoutHeight = 0; 355 int maxLayoutHeight = -1; 356 switch (heightMode) { 357 case MeasureSpec.EXACTLY: 358 layoutHeight = maxLayoutHeight = heightSize - getPaddingTop() - getPaddingBottom(); 359 break; 360 case MeasureSpec.AT_MOST: 361 maxLayoutHeight = heightSize - getPaddingTop() - getPaddingBottom(); 362 break; 363 } 364 365 float weightSum = 0; 366 boolean canSlide = false; 367 int widthRemaining = widthSize - getPaddingLeft() - getPaddingRight(); 368 final int childCount = getChildCount(); 369 370 if (childCount > 2) { 371 Log.e(TAG, "onMeasure: More than two child views are not supported."); 372 } 373 374 // We'll find the current one below. 375 mSlideableView = null; 376 377 // First pass. Measure based on child LayoutParams width/height. 378 // Weight will incur a second pass. 379 for (int i = 0; i < childCount; i++) { 380 final View child = getChildAt(i); 381 final LayoutParams lp = (LayoutParams) child.getLayoutParams(); 382 383 if (child.getVisibility() == GONE) { 384 lp.dimWhenOffset = false; 385 continue; 386 } 387 388 if (lp.weight > 0) { 389 weightSum += lp.weight; 390 391 // If we have no width, weight is the only contributor to the final size. 392 // Measure this view on the weight pass only. 393 if (lp.width == 0) continue; 394 } 395 396 int childWidthSpec; 397 final int horizontalMargin = lp.leftMargin + lp.rightMargin; 398 if (lp.width == LayoutParams.WRAP_CONTENT) { 399 childWidthSpec = MeasureSpec.makeMeasureSpec(widthSize - horizontalMargin, 400 MeasureSpec.AT_MOST); 401 } else if (lp.width == LayoutParams.FILL_PARENT) { 402 childWidthSpec = MeasureSpec.makeMeasureSpec(widthSize - horizontalMargin, 403 MeasureSpec.EXACTLY); 404 } else { 405 childWidthSpec = MeasureSpec.makeMeasureSpec(lp.width, MeasureSpec.EXACTLY); 406 } 407 408 int childHeightSpec; 409 if (lp.height == LayoutParams.WRAP_CONTENT) { 410 childHeightSpec = MeasureSpec.makeMeasureSpec(maxLayoutHeight, MeasureSpec.AT_MOST); 411 } else if (lp.height == LayoutParams.FILL_PARENT) { 412 childHeightSpec = MeasureSpec.makeMeasureSpec(maxLayoutHeight, MeasureSpec.EXACTLY); 413 } else { 414 childHeightSpec = MeasureSpec.makeMeasureSpec(lp.height, MeasureSpec.EXACTLY); 415 } 416 417 child.measure(childWidthSpec, childHeightSpec); 418 final int childWidth = child.getMeasuredWidth(); 419 final int childHeight = child.getMeasuredHeight(); 420 421 if (heightMode == MeasureSpec.AT_MOST && childHeight > layoutHeight) { 422 layoutHeight = Math.min(childHeight, maxLayoutHeight); 423 } 424 425 widthRemaining -= childWidth; 426 canSlide |= lp.slideable = widthRemaining < 0; 427 if (lp.slideable) { 428 mSlideableView = child; 429 } 430 } 431 432 // Resolve weight and make sure non-sliding panels are smaller than the full screen. 433 if (canSlide || weightSum > 0) { 434 final int fixedPanelWidthLimit = widthSize - mOverhangSize; 435 436 for (int i = 0; i < childCount; i++) { 437 final View child = getChildAt(i); 438 439 if (child.getVisibility() == GONE) { 440 continue; 441 } 442 443 final LayoutParams lp = (LayoutParams) child.getLayoutParams(); 444 445 final boolean skippedFirstPass = lp.width == 0 && lp.weight > 0; 446 final int measuredWidth = skippedFirstPass ? 0 : child.getMeasuredWidth(); 447 if (canSlide && child != mSlideableView) { 448 if (lp.width < 0 && (measuredWidth > fixedPanelWidthLimit || lp.weight > 0)) { 449 // Fixed panels in a sliding configuration should 450 // be clamped to the fixed panel limit. 451 final int childHeightSpec; 452 if (skippedFirstPass) { 453 // Do initial height measurement if we skipped measuring this view 454 // the first time around. 455 if (lp.height == LayoutParams.WRAP_CONTENT) { 456 childHeightSpec = MeasureSpec.makeMeasureSpec(maxLayoutHeight, 457 MeasureSpec.AT_MOST); 458 } else if (lp.height == LayoutParams.FILL_PARENT) { 459 childHeightSpec = MeasureSpec.makeMeasureSpec(maxLayoutHeight, 460 MeasureSpec.EXACTLY); 461 } else { 462 childHeightSpec = MeasureSpec.makeMeasureSpec(lp.height, 463 MeasureSpec.EXACTLY); 464 } 465 } else { 466 childHeightSpec = MeasureSpec.makeMeasureSpec( 467 child.getMeasuredHeight(), MeasureSpec.EXACTLY); 468 } 469 final int childWidthSpec = MeasureSpec.makeMeasureSpec( 470 fixedPanelWidthLimit, MeasureSpec.EXACTLY); 471 child.measure(childWidthSpec, childHeightSpec); 472 } 473 } else if (lp.weight > 0) { 474 int childHeightSpec; 475 if (lp.width == 0) { 476 // This was skipped the first time; figure out a real height spec. 477 if (lp.height == LayoutParams.WRAP_CONTENT) { 478 childHeightSpec = MeasureSpec.makeMeasureSpec(maxLayoutHeight, 479 MeasureSpec.AT_MOST); 480 } else if (lp.height == LayoutParams.FILL_PARENT) { 481 childHeightSpec = MeasureSpec.makeMeasureSpec(maxLayoutHeight, 482 MeasureSpec.EXACTLY); 483 } else { 484 childHeightSpec = MeasureSpec.makeMeasureSpec(lp.height, 485 MeasureSpec.EXACTLY); 486 } 487 } else { 488 childHeightSpec = MeasureSpec.makeMeasureSpec( 489 child.getMeasuredHeight(), MeasureSpec.EXACTLY); 490 } 491 492 if (canSlide) { 493 // Consume available space 494 final int horizontalMargin = lp.leftMargin + lp.rightMargin; 495 final int newWidth = widthSize - horizontalMargin; 496 final int childWidthSpec = MeasureSpec.makeMeasureSpec( 497 newWidth, MeasureSpec.EXACTLY); 498 if (measuredWidth != newWidth) { 499 child.measure(childWidthSpec, childHeightSpec); 500 } 501 } else { 502 // Distribute the extra width proportionally similar to LinearLayout 503 final int widthToDistribute = Math.max(0, widthRemaining); 504 final int addedWidth = (int) (lp.weight * widthToDistribute / weightSum); 505 final int childWidthSpec = MeasureSpec.makeMeasureSpec( 506 measuredWidth + addedWidth, MeasureSpec.EXACTLY); 507 child.measure(childWidthSpec, childHeightSpec); 508 } 509 } 510 } 511 } 512 513 setMeasuredDimension(widthSize, layoutHeight); 514 mCanSlide = canSlide; 515 if (mDragHelper.getViewDragState() != ViewDragHelper.STATE_IDLE && !canSlide) { 516 // Cancel scrolling in progress, it's no longer relevant. 517 mDragHelper.abort(); 518 } 519 } 520 521 @Override 522 protected void onLayout(boolean changed, int l, int t, int r, int b) { 523 final int width = r - l; 524 final int paddingLeft = getPaddingLeft(); 525 final int paddingRight = getPaddingRight(); 526 final int paddingTop = getPaddingTop(); 527 528 final int childCount = getChildCount(); 529 int xStart = paddingLeft; 530 int nextXStart = xStart; 531 532 for (int i = 0; i < childCount; i++) { 533 final View child = getChildAt(i); 534 535 if (child.getVisibility() == GONE) { 536 continue; 537 } 538 539 final LayoutParams lp = (LayoutParams) child.getLayoutParams(); 540 541 final int childWidth = child.getMeasuredWidth(); 542 int offset = 0; 543 544 if (lp.slideable) { 545 final int margin = lp.leftMargin + lp.rightMargin; 546 final int range = Math.min(nextXStart, 547 width - paddingRight - mOverhangSize) - xStart - margin; 548 mSlideRange = range; 549 lp.dimWhenOffset = xStart + lp.leftMargin + range + childWidth / 2 > 550 width - paddingRight; 551 xStart += (int) (range * mSlideOffset) + lp.leftMargin; 552 } else if (mCanSlide && mParallaxBy != 0) { 553 offset = (int) ((1 - mSlideOffset) * mParallaxBy); 554 xStart = nextXStart; 555 } else { 556 xStart = nextXStart; 557 } 558 559 final int childLeft = xStart - offset; 560 final int childRight = childLeft + childWidth; 561 final int childTop = paddingTop; 562 final int childBottom = childTop + child.getMeasuredHeight(); 563 child.layout(childLeft, paddingTop, childRight, childBottom); 564 565 nextXStart += child.getWidth(); 566 } 567 568 if (mFirstLayout && mCanSlide) { 569 mSlideOffset = mPreservedOpenState ? 1.f : 0; 570 if (mParallaxBy != 0) { 571 parallaxOtherViews(mSlideOffset); 572 } 573 if (((LayoutParams) mSlideableView.getLayoutParams()).dimWhenOffset) { 574 dimChildView(mSlideableView, mSlideOffset, mSliderFadeColor); 575 } 576 } 577 578 mFirstLayout = false; 579 } 580 581 @Override 582 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 583 super.onSizeChanged(w, h, oldw, oldh); 584 // Recalculate sliding panes and their details 585 mFirstLayout = true; 586 } 587 588 @Override 589 public void requestChildFocus(View child, View focused) { 590 super.requestChildFocus(child, focused); 591 if (!isInTouchMode() && !mCanSlide) { 592 mPreservedOpenState = child == mSlideableView; 593 } 594 } 595 596 @Override 597 public boolean onInterceptTouchEvent(MotionEvent ev) { 598 final int action = MotionEventCompat.getActionMasked(ev); 599 600 // Preserve the open state based on the last view that was touched. 601 if (!mCanSlide && action == MotionEvent.ACTION_DOWN && getChildCount() > 1) { 602 // After the first things will be slideable. 603 final View secondChild = getChildAt(1); 604 if (secondChild != null) { 605 mPreservedOpenState = !mDragHelper.isViewUnder(secondChild, 606 (int) ev.getX(), (int) ev.getY()); 607 } 608 } 609 610 if (!mCanSlide || (mIsUnableToDrag && action != MotionEvent.ACTION_DOWN)) { 611 mDragHelper.cancel(); 612 return super.onInterceptTouchEvent(ev); 613 } 614 615 if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) { 616 mDragHelper.cancel(); 617 return false; 618 } 619 620 boolean interceptTap = false; 621 622 switch (action) { 623 case MotionEvent.ACTION_DOWN: { 624 mIsUnableToDrag = false; 625 final float x = ev.getX(); 626 final float y = ev.getY(); 627 mInitialMotionX = x; 628 mInitialMotionY = y; 629 630 if (mDragHelper.isViewUnder(mSlideableView, (int) x, (int) y) && 631 isDimmed(mSlideableView)) { 632 interceptTap = true; 633 } 634 break; 635 } 636 637 case MotionEvent.ACTION_MOVE: { 638 final float x = ev.getX(); 639 final float y = ev.getY(); 640 final float adx = Math.abs(x - mInitialMotionX); 641 final float ady = Math.abs(y - mInitialMotionY); 642 final int slop = mDragHelper.getTouchSlop(); 643 if (adx > slop && ady > adx) { 644 mDragHelper.cancel(); 645 mIsUnableToDrag = true; 646 return false; 647 } 648 } 649 } 650 651 final boolean interceptForDrag = mDragHelper.shouldInterceptTouchEvent(ev); 652 653 return interceptForDrag || interceptTap; 654 } 655 656 @Override 657 public boolean onTouchEvent(MotionEvent ev) { 658 if (!mCanSlide) { 659 return super.onTouchEvent(ev); 660 } 661 662 mDragHelper.processTouchEvent(ev); 663 664 final int action = ev.getAction(); 665 boolean wantTouchEvents = true; 666 667 switch (action & MotionEventCompat.ACTION_MASK) { 668 case MotionEvent.ACTION_DOWN: { 669 final float x = ev.getX(); 670 final float y = ev.getY(); 671 mInitialMotionX = x; 672 mInitialMotionY = y; 673 break; 674 } 675 676 case MotionEvent.ACTION_UP: { 677 if (isDimmed(mSlideableView)) { 678 final float x = ev.getX(); 679 final float y = ev.getY(); 680 final float dx = x - mInitialMotionX; 681 final float dy = y - mInitialMotionY; 682 final int slop = mDragHelper.getTouchSlop(); 683 if (dx * dx + dy * dy < slop * slop && 684 mDragHelper.isViewUnder(mSlideableView, (int) x, (int) y)) { 685 // Taps close a dimmed open pane. 686 closePane(mSlideableView, 0); 687 break; 688 } 689 } 690 break; 691 } 692 } 693 694 return wantTouchEvents; 695 } 696 697 private boolean closePane(View pane, int initialVelocity) { 698 if (mFirstLayout || smoothSlideTo(0.f, initialVelocity)) { 699 mPreservedOpenState = false; 700 return true; 701 } 702 return false; 703 } 704 705 private boolean openPane(View pane, int initialVelocity) { 706 if (mFirstLayout || smoothSlideTo(1.f, initialVelocity)) { 707 mPreservedOpenState = true; 708 return true; 709 } 710 return false; 711 } 712 713 /** 714 * @deprecated Renamed to {@link #openPane()} - this method is going away soon! 715 */ 716 @Deprecated 717 public void smoothSlideOpen() { 718 openPane(); 719 } 720 721 /** 722 * Open the sliding pane if it is currently slideable. If first layout 723 * has already completed this will animate. 724 * 725 * @return true if the pane was slideable and is now open/in the process of opening 726 */ 727 public boolean openPane() { 728 return openPane(mSlideableView, 0); 729 } 730 731 /** 732 * @deprecated Renamed to {@link #closePane()} - this method is going away soon! 733 */ 734 @Deprecated 735 public void smoothSlideClosed() { 736 closePane(); 737 } 738 739 /** 740 * Close the sliding pane if it is currently slideable. If first layout 741 * has already completed this will animate. 742 * 743 * @return true if the pane was slideable and is now closed/in the process of closing 744 */ 745 public boolean closePane() { 746 return closePane(mSlideableView, 0); 747 } 748 749 /** 750 * Check if the layout is completely open. It can be open either because the slider 751 * itself is open revealing the left pane, or if all content fits without sliding. 752 * 753 * @return true if sliding panels are completely open 754 */ 755 public boolean isOpen() { 756 return !mCanSlide || mSlideOffset == 1; 757 } 758 759 /** 760 * @return true if content in this layout can be slid open and closed 761 * @deprecated Renamed to {@link #isSlideable()} - this method is going away soon! 762 */ 763 @Deprecated 764 public boolean canSlide() { 765 return mCanSlide; 766 } 767 768 /** 769 * Check if the content in this layout cannot fully fit side by side and therefore 770 * the content pane can be slid back and forth. 771 * 772 * @return true if content in this layout can be slid open and closed 773 */ 774 public boolean isSlideable() { 775 return mCanSlide; 776 } 777 778 private boolean performDrag(int newLeft) { 779 final LayoutParams lp = (LayoutParams) mSlideableView.getLayoutParams(); 780 final int leftBound = getPaddingLeft() + lp.leftMargin; 781 782 final float oldLeft = mSlideableView.getLeft(); 783 784 final int dxPane = (int) (newLeft - oldLeft); 785 786 mSlideableView.offsetLeftAndRight(dxPane); 787 788 mSlideOffset = (float) (newLeft - leftBound) / mSlideRange; 789 790 if (mParallaxBy != 0) { 791 parallaxOtherViews(mSlideOffset); 792 } 793 794 if (lp.dimWhenOffset) { 795 dimChildView(mSlideableView, mSlideOffset, mSliderFadeColor); 796 } 797 dispatchOnPanelSlide(mSlideableView); 798 799 return true; 800 } 801 802 private void dimChildView(View v, float mag, int fadeColor) { 803 final LayoutParams lp = (LayoutParams) v.getLayoutParams(); 804 805 if (mag > 0 && fadeColor != 0) { 806 final int baseAlpha = (fadeColor & 0xff000000) >>> 24; 807 int imag = (int) (baseAlpha * mag); 808 int color = imag << 24 | (fadeColor & 0xffffff); 809 if (lp.dimPaint == null) { 810 lp.dimPaint = new Paint(); 811 } 812 lp.dimPaint.setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.SRC_OVER)); 813 if (ViewCompat.getLayerType(v) != ViewCompat.LAYER_TYPE_HARDWARE) { 814 ViewCompat.setLayerType(v, ViewCompat.LAYER_TYPE_HARDWARE, lp.dimPaint); 815 } 816 invalidateChildRegion(v); 817 } else if (ViewCompat.getLayerType(v) != ViewCompat.LAYER_TYPE_NONE) { 818 ViewCompat.setLayerType(v, ViewCompat.LAYER_TYPE_NONE, null); 819 } 820 } 821 822 @Override 823 protected boolean drawChild(Canvas canvas, View child, long drawingTime) { 824 final LayoutParams lp = (LayoutParams) child.getLayoutParams(); 825 boolean result; 826 final int save = canvas.save(Canvas.CLIP_SAVE_FLAG); 827 828 if (mCanSlide && !lp.slideable && mSlideableView != null) { 829 // Clip against the slider; no sense drawing what will immediately be covered. 830 canvas.getClipBounds(mTmpRect); 831 mTmpRect.right = Math.min(mTmpRect.right, mSlideableView.getLeft()); 832 canvas.clipRect(mTmpRect); 833 } 834 835 if (Build.VERSION.SDK_INT >= 11) { // HC 836 result = super.drawChild(canvas, child, drawingTime); 837 } else { 838 if (lp.dimWhenOffset && mSlideOffset > 0) { 839 if (!child.isDrawingCacheEnabled()) { 840 child.setDrawingCacheEnabled(true); 841 } 842 final Bitmap cache = child.getDrawingCache(); 843 canvas.drawBitmap(cache, child.getLeft(), child.getTop(), lp.dimPaint); 844 result = false; 845 } else { 846 if (child.isDrawingCacheEnabled()) { 847 child.setDrawingCacheEnabled(false); 848 } 849 result = super.drawChild(canvas, child, drawingTime); 850 } 851 } 852 853 canvas.restoreToCount(save); 854 855 return result; 856 } 857 858 private void invalidateChildRegion(View v) { 859 IMPL.invalidateChildRegion(this, v); 860 } 861 862 /** 863 * Smoothly animate mDraggingPane to the target X position within its range. 864 * 865 * @param slideOffset position to animate to 866 * @param velocity initial velocity in case of fling, or 0. 867 */ 868 boolean smoothSlideTo(float slideOffset, int velocity) { 869 if (!mCanSlide) { 870 // Nothing to do. 871 return false; 872 } 873 874 final LayoutParams lp = (LayoutParams) mSlideableView.getLayoutParams(); 875 876 final int leftBound = getPaddingLeft() + lp.leftMargin; 877 int x = (int) (leftBound + slideOffset * mSlideRange); 878 879 if (mDragHelper.smoothSlideViewTo(mSlideableView, x, mSlideableView.getTop())) { 880 ViewCompat.postInvalidateOnAnimation(this); 881 return true; 882 } 883 return false; 884 } 885 886 @Override 887 public void computeScroll() { 888 if (mDragHelper.continueSettling(true)) { 889 if (!mCanSlide) { 890 mDragHelper.abort(); 891 return; 892 } 893 894 ViewCompat.postInvalidateOnAnimation(this); 895 } 896 } 897 898 /** 899 * Set a drawable to use as a shadow cast by the right pane onto the left pane 900 * during opening/closing. 901 * 902 * @param d drawable to use as a shadow 903 */ 904 public void setShadowDrawable(Drawable d) { 905 mShadowDrawable = d; 906 } 907 908 /** 909 * Set a drawable to use as a shadow cast by the right pane onto the left pane 910 * during opening/closing. 911 * 912 * @param resId Resource ID of a drawable to use 913 */ 914 public void setShadowResource(int resId) { 915 setShadowDrawable(getResources().getDrawable(resId)); 916 } 917 918 @Override 919 public void draw(Canvas c) { 920 super.draw(c); 921 922 final View shadowView = getChildCount() > 1 ? getChildAt(1) : null; 923 if (shadowView == null || mShadowDrawable == null) { 924 // No need to draw a shadow if we don't have one. 925 return; 926 } 927 928 final int shadowWidth = mShadowDrawable.getIntrinsicWidth(); 929 final int right = shadowView.getLeft(); 930 final int top = shadowView.getTop(); 931 final int bottom = shadowView.getBottom(); 932 final int left = right - shadowWidth; 933 mShadowDrawable.setBounds(left, top, right, bottom); 934 mShadowDrawable.draw(c); 935 } 936 937 private void parallaxOtherViews(float slideOffset) { 938 final LayoutParams slideLp = (LayoutParams) mSlideableView.getLayoutParams(); 939 final boolean dimViews = slideLp.dimWhenOffset && slideLp.leftMargin <= 0; 940 final int childCount = getChildCount(); 941 for (int i = 0; i < childCount; i++) { 942 final View v = getChildAt(i); 943 if (v == mSlideableView) continue; 944 945 final int oldOffset = (int) ((1 - mParallaxOffset) * mParallaxBy); 946 mParallaxOffset = slideOffset; 947 final int newOffset = (int) ((1 - slideOffset) * mParallaxBy); 948 final int dx = oldOffset - newOffset; 949 950 v.offsetLeftAndRight(dx); 951 952 if (dimViews) { 953 dimChildView(v, 1 - mParallaxOffset, mCoveredFadeColor); 954 } 955 } 956 } 957 958 /** 959 * Tests scrollability within child views of v given a delta of dx. 960 * 961 * @param v View to test for horizontal scrollability 962 * @param checkV Whether the view v passed should itself be checked for scrollability (true), 963 * or just its children (false). 964 * @param dx Delta scrolled in pixels 965 * @param x X coordinate of the active touch point 966 * @param y Y coordinate of the active touch point 967 * @return true if child views of v can be scrolled by delta of dx. 968 */ 969 protected boolean canScroll(View v, boolean checkV, int dx, int x, int y) { 970 if (v instanceof ViewGroup) { 971 final ViewGroup group = (ViewGroup) v; 972 final int scrollX = v.getScrollX(); 973 final int scrollY = v.getScrollY(); 974 final int count = group.getChildCount(); 975 // Count backwards - let topmost views consume scroll distance first. 976 for (int i = count - 1; i >= 0; i--) { 977 // TODO: Add versioned support here for transformed views. 978 // This will not work for transformed views in Honeycomb+ 979 final View child = group.getChildAt(i); 980 if (x + scrollX >= child.getLeft() && x + scrollX < child.getRight() && 981 y + scrollY >= child.getTop() && y + scrollY < child.getBottom() && 982 canScroll(child, true, dx, x + scrollX - child.getLeft(), 983 y + scrollY - child.getTop())) { 984 return true; 985 } 986 } 987 } 988 989 return checkV && ViewCompat.canScrollHorizontally(v, -dx); 990 } 991 992 boolean isDimmed(View child) { 993 if (child == null) { 994 return false; 995 } 996 final LayoutParams lp = (LayoutParams) child.getLayoutParams(); 997 return mCanSlide && lp.dimWhenOffset && mSlideOffset > 0; 998 } 999 1000 @Override 1001 protected ViewGroup.LayoutParams generateDefaultLayoutParams() { 1002 return new LayoutParams(); 1003 } 1004 1005 @Override 1006 protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) { 1007 return p instanceof MarginLayoutParams 1008 ? new LayoutParams((MarginLayoutParams) p) 1009 : new LayoutParams(p); 1010 } 1011 1012 @Override 1013 protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { 1014 return p instanceof LayoutParams && super.checkLayoutParams(p); 1015 } 1016 1017 @Override 1018 public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) { 1019 return new LayoutParams(getContext(), attrs); 1020 } 1021 1022 @Override 1023 protected Parcelable onSaveInstanceState() { 1024 Parcelable superState = super.onSaveInstanceState(); 1025 1026 SavedState ss = new SavedState(superState); 1027 ss.isOpen = isSlideable() ? isOpen() : mPreservedOpenState; 1028 1029 return ss; 1030 } 1031 1032 @Override 1033 protected void onRestoreInstanceState(Parcelable state) { 1034 SavedState ss = (SavedState) state; 1035 super.onRestoreInstanceState(ss.getSuperState()); 1036 1037 if (ss.isOpen) { 1038 openPane(); 1039 } else { 1040 closePane(); 1041 } 1042 mPreservedOpenState = ss.isOpen; 1043 } 1044 1045 private class DragHelperCallback extends ViewDragHelper.Callback { 1046 1047 @Override 1048 public boolean tryCaptureView(View child, int pointerId) { 1049 if (mIsUnableToDrag) { 1050 return false; 1051 } 1052 1053 return ((LayoutParams) child.getLayoutParams()).slideable; 1054 } 1055 1056 @Override 1057 public void onViewDragStateChanged(int state) { 1058 if (mDragHelper.getViewDragState() == ViewDragHelper.STATE_IDLE) { 1059 if (mSlideOffset == 0) { 1060 dispatchOnPanelClosed(mSlideableView); 1061 } else { 1062 dispatchOnPanelOpened(mSlideableView); 1063 } 1064 } 1065 } 1066 1067 @Override 1068 public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) { 1069 performDrag(left); 1070 invalidate(); 1071 } 1072 1073 @Override 1074 public void onViewReleased(View releasedChild, float xvel, float yvel) { 1075 final LayoutParams lp = (LayoutParams) releasedChild.getLayoutParams(); 1076 int left = getPaddingLeft() + lp.leftMargin; 1077 if (xvel > 0 || (xvel == 0 && mSlideOffset > 0.5f)) { 1078 left += mSlideRange; 1079 } 1080 mDragHelper.settleCapturedViewAt(left, releasedChild.getTop()); 1081 invalidate(); 1082 } 1083 1084 @Override 1085 public int getViewHorizontalDragRange(View child) { 1086 return mSlideRange; 1087 } 1088 1089 @Override 1090 public int clampViewPositionHorizontal(View child, int left, int dx) { 1091 final LayoutParams lp = (LayoutParams) mSlideableView.getLayoutParams(); 1092 final int leftBound = getPaddingLeft() + lp.leftMargin; 1093 final int rightBound = leftBound + mSlideRange; 1094 1095 final int newLeft = Math.min(Math.max(left, leftBound), rightBound); 1096 1097 return newLeft; 1098 } 1099 1100 @Override 1101 public void onEdgeDragStarted(int edgeFlags, int pointerId) { 1102 mDragHelper.captureChildView(mSlideableView, pointerId); 1103 } 1104 } 1105 1106 public static class LayoutParams extends ViewGroup.MarginLayoutParams { 1107 private static final int[] ATTRS = new int[] { 1108 android.R.attr.layout_weight 1109 }; 1110 1111 /** 1112 * The weighted proportion of how much of the leftover space 1113 * this child should consume after measurement. 1114 */ 1115 public float weight = 0; 1116 1117 /** 1118 * True if this pane is the slideable pane in the layout. 1119 */ 1120 boolean slideable; 1121 1122 /** 1123 * True if this view should be drawn dimmed 1124 * when it's been offset from its default position. 1125 */ 1126 boolean dimWhenOffset; 1127 1128 Paint dimPaint; 1129 1130 public LayoutParams() { 1131 super(FILL_PARENT, FILL_PARENT); 1132 } 1133 1134 public LayoutParams(int width, int height) { 1135 super(width, height); 1136 } 1137 1138 public LayoutParams(android.view.ViewGroup.LayoutParams source) { 1139 super(source); 1140 } 1141 1142 public LayoutParams(MarginLayoutParams source) { 1143 super(source); 1144 } 1145 1146 public LayoutParams(LayoutParams source) { 1147 super(source); 1148 this.weight = source.weight; 1149 } 1150 1151 public LayoutParams(Context c, AttributeSet attrs) { 1152 super(c, attrs); 1153 1154 final TypedArray a = c.obtainStyledAttributes(attrs, ATTRS); 1155 this.weight = a.getFloat(0, 0); 1156 a.recycle(); 1157 } 1158 1159 } 1160 1161 static class SavedState extends BaseSavedState { 1162 boolean isOpen; 1163 1164 SavedState(Parcelable superState) { 1165 super(superState); 1166 } 1167 1168 private SavedState(Parcel in) { 1169 super(in); 1170 isOpen = in.readInt() != 0; 1171 } 1172 1173 @Override 1174 public void writeToParcel(Parcel out, int flags) { 1175 super.writeToParcel(out, flags); 1176 out.writeInt(isOpen ? 1 : 0); 1177 } 1178 1179 public static final Parcelable.Creator<SavedState> CREATOR = 1180 new Parcelable.Creator<SavedState>() { 1181 public SavedState createFromParcel(Parcel in) { 1182 return new SavedState(in); 1183 } 1184 1185 public SavedState[] newArray(int size) { 1186 return new SavedState[size]; 1187 } 1188 }; 1189 } 1190 1191 interface SlidingPanelLayoutImpl { 1192 void invalidateChildRegion(SlidingPaneLayout parent, View child); 1193 } 1194 1195 static class SlidingPanelLayoutImplBase implements SlidingPanelLayoutImpl { 1196 public void invalidateChildRegion(SlidingPaneLayout parent, View child) { 1197 ViewCompat.postInvalidateOnAnimation(parent, child.getLeft(), child.getTop(), 1198 child.getRight(), child.getBottom()); 1199 } 1200 } 1201 1202 static class SlidingPanelLayoutImplJB extends SlidingPanelLayoutImplBase { 1203 /* 1204 * Private API hacks! Nasty! Bad! 1205 * 1206 * In Jellybean, some optimizations in the hardware UI renderer 1207 * prevent a changed Paint on a View using a hardware layer from having 1208 * the intended effect. This twiddles some internal bits on the view to force 1209 * it to recreate the display list. 1210 */ 1211 private Method mGetDisplayList; 1212 private Field mRecreateDisplayList; 1213 1214 SlidingPanelLayoutImplJB() { 1215 try { 1216 mGetDisplayList = View.class.getDeclaredMethod("getDisplayList", (Class[]) null); 1217 } catch (NoSuchMethodException e) { 1218 Log.e(TAG, "Couldn't fetch getDisplayList method; dimming won't work right.", e); 1219 } 1220 try { 1221 mRecreateDisplayList = View.class.getDeclaredField("mRecreateDisplayList"); 1222 mRecreateDisplayList.setAccessible(true); 1223 } catch (NoSuchFieldException e) { 1224 Log.e(TAG, "Couldn't fetch mRecreateDisplayList field; dimming will be slow.", e); 1225 } 1226 } 1227 1228 @Override 1229 public void invalidateChildRegion(SlidingPaneLayout parent, View child) { 1230 if (mGetDisplayList != null && mRecreateDisplayList != null) { 1231 try { 1232 mRecreateDisplayList.setBoolean(child, true); 1233 mGetDisplayList.invoke(child, (Object[]) null); 1234 } catch (Exception e) { 1235 Log.e(TAG, "Error refreshing display list state", e); 1236 } 1237 } else { 1238 // Slow path. REALLY slow path. Let's hope we don't get here. 1239 child.invalidate(); 1240 return; 1241 } 1242 super.invalidateChildRegion(parent, child); 1243 } 1244 } 1245 1246 static class SlidingPanelLayoutImplJBMR1 extends SlidingPanelLayoutImplBase { 1247 @Override 1248 public void invalidateChildRegion(SlidingPaneLayout parent, View child) { 1249 ViewCompat.setLayerPaint(child, ((LayoutParams) child.getLayoutParams()).dimPaint); 1250 } 1251 } 1252} 1253