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