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