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