NotificationStackScrollLayout.java revision 2580a976ec93a01ed00fae51364ad872bc591d95
1/*
2 * Copyright (C) 2014 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 com.android.systemui.statusbar.stack;
18
19import android.content.Context;
20import android.content.res.Configuration;
21import android.graphics.Canvas;
22import android.graphics.Paint;
23import android.util.AttributeSet;
24import android.util.Log;
25import android.view.MotionEvent;
26import android.view.VelocityTracker;
27import android.view.View;
28import android.view.ViewConfiguration;
29import android.view.ViewGroup;
30import android.view.ViewTreeObserver;
31import android.view.animation.AnimationUtils;
32import android.widget.OverScroller;
33import com.android.systemui.ExpandHelper;
34import com.android.systemui.R;
35import com.android.systemui.SwipeHelper;
36import com.android.systemui.statusbar.ActivatableNotificationView;
37import com.android.systemui.statusbar.ExpandableNotificationRow;
38import com.android.systemui.statusbar.ExpandableView;
39import com.android.systemui.statusbar.SpeedBumpView;
40import com.android.systemui.statusbar.policy.ScrollAdapter;
41import com.android.systemui.statusbar.stack.StackScrollState.ViewState;
42
43import java.util.ArrayList;
44
45/**
46 * A layout which handles a dynamic amount of notifications and presents them in a scrollable stack.
47 */
48public class NotificationStackScrollLayout extends ViewGroup
49        implements SwipeHelper.Callback, ExpandHelper.Callback, ScrollAdapter,
50        ExpandableView.OnHeightChangedListener {
51
52    private static final String TAG = "NotificationStackScrollLayout";
53    private static final boolean DEBUG = false;
54    private static final float RUBBER_BAND_FACTOR_NORMAL = 0.35f;
55    private static final float RUBBER_BAND_FACTOR_AFTER_EXPAND = 0.15f;
56    private static final float RUBBER_BAND_FACTOR_ON_PANEL_EXPAND = 0.21f;
57
58    /**
59     * Sentinel value for no current active pointer. Used by {@link #mActivePointerId}.
60     */
61    private static final int INVALID_POINTER = -1;
62
63    private ExpandHelper mExpandHelper;
64    private SwipeHelper mSwipeHelper;
65    private boolean mSwipingInProgress;
66    private int mCurrentStackHeight = Integer.MAX_VALUE;
67    private int mOwnScrollY;
68    private int mMaxLayoutHeight;
69
70    private VelocityTracker mVelocityTracker;
71    private OverScroller mScroller;
72    private int mTouchSlop;
73    private int mMinimumVelocity;
74    private int mMaximumVelocity;
75    private int mOverflingDistance;
76    private float mMaxOverScroll;
77    private boolean mIsBeingDragged;
78    private int mLastMotionY;
79    private int mDownX;
80    private int mActivePointerId;
81
82    private int mSidePaddings;
83    private Paint mDebugPaint;
84    private int mContentHeight;
85    private int mCollapsedSize;
86    private int mBottomStackSlowDownHeight;
87    private int mBottomStackPeekSize;
88    private int mPaddingBetweenElements;
89    private int mPaddingBetweenElementsDimmed;
90    private int mPaddingBetweenElementsNormal;
91    private int mTopPadding;
92
93    /**
94     * The algorithm which calculates the properties for our children
95     */
96    private StackScrollAlgorithm mStackScrollAlgorithm;
97
98    /**
99     * The current State this Layout is in
100     */
101    private StackScrollState mCurrentStackScrollState = new StackScrollState(this);
102    private AmbientState mAmbientState = new AmbientState();
103    private ArrayList<View> mChildrenToAddAnimated = new ArrayList<View>();
104    private ArrayList<View> mChildrenToRemoveAnimated = new ArrayList<View>();
105    private ArrayList<View> mSnappedBackChildren = new ArrayList<View>();
106    private ArrayList<View> mDragAnimPendingChildren = new ArrayList<View>();
107    private ArrayList<View> mChildrenChangingPositions = new ArrayList<View>();
108    private ArrayList<AnimationEvent> mAnimationEvents
109            = new ArrayList<AnimationEvent>();
110    private ArrayList<View> mSwipedOutViews = new ArrayList<View>();
111    private final StackStateAnimator mStateAnimator = new StackStateAnimator(this);
112    private boolean mAnimationsEnabled;
113    private boolean mChangePositionInProgress;
114
115    /**
116     * The raw amount of the overScroll on the top, which is not rubber-banded.
117     */
118    private float mOverScrolledTopPixels;
119
120    /**
121     * The raw amount of the overScroll on the bottom, which is not rubber-banded.
122     */
123    private float mOverScrolledBottomPixels;
124
125    private OnChildLocationsChangedListener mListener;
126    private OnOverscrollTopChangedListener mOverscrollTopChangedListener;
127    private ExpandableView.OnHeightChangedListener mOnHeightChangedListener;
128    private boolean mNeedsAnimation;
129    private boolean mTopPaddingNeedsAnimation;
130    private boolean mDimmedNeedsAnimation;
131    private boolean mDarkNeedsAnimation;
132    private boolean mActivateNeedsAnimation;
133    private boolean mIsExpanded = true;
134    private boolean mChildrenUpdateRequested;
135    private SpeedBumpView mSpeedBumpView;
136    private boolean mIsExpansionChanging;
137    private boolean mExpandingNotification;
138    private boolean mExpandedInThisMotion;
139    private boolean mScrollingEnabled;
140
141    /**
142     * Was the scroller scrolled to the top when the down motion was observed?
143     */
144    private boolean mScrolledToTopOnFirstDown;
145
146    /**
147     * The minimal amount of over scroll which is needed in order to switch to the quick settings
148     * when over scrolling on a expanded card.
149     */
150    private float mMinTopOverScrollToEscape;
151    private int mIntrinsicPadding;
152    private int mNotificationTopPadding;
153    private int mMinStackHeight;
154    private boolean mDontReportNextOverScroll;
155
156    /**
157     * The maximum scrollPosition which we are allowed to reach when a notification was expanded.
158     * This is needed to avoid scrolling too far after the notification was collapsed in the same
159     * motion.
160     */
161    private int mMaxScrollAfterExpand;
162    private OnLongClickListener mLongClickListener;
163
164    /**
165     * Should in this touch motion only be scrolling allowed? It's true when the scroller was
166     * animating.
167     */
168    private boolean mOnlyScrollingInThisMotion;
169    private boolean mTouchEnabled = true;
170    private ViewTreeObserver.OnPreDrawListener mChildrenUpdater
171            = new ViewTreeObserver.OnPreDrawListener() {
172        @Override
173        public boolean onPreDraw() {
174            updateChildren();
175            mChildrenUpdateRequested = false;
176            getViewTreeObserver().removeOnPreDrawListener(this);
177            return true;
178        }
179    };
180
181    public NotificationStackScrollLayout(Context context) {
182        this(context, null);
183    }
184
185    public NotificationStackScrollLayout(Context context, AttributeSet attrs) {
186        this(context, attrs, 0);
187    }
188
189    public NotificationStackScrollLayout(Context context, AttributeSet attrs, int defStyleAttr) {
190        this(context, attrs, defStyleAttr, 0);
191    }
192
193    public NotificationStackScrollLayout(Context context, AttributeSet attrs, int defStyleAttr,
194            int defStyleRes) {
195        super(context, attrs, defStyleAttr, defStyleRes);
196        initView(context);
197        if (DEBUG) {
198            setWillNotDraw(false);
199            mDebugPaint = new Paint();
200            mDebugPaint.setColor(0xffff0000);
201            mDebugPaint.setStrokeWidth(2);
202            mDebugPaint.setStyle(Paint.Style.STROKE);
203        }
204    }
205
206    @Override
207    protected void onDraw(Canvas canvas) {
208        if (DEBUG) {
209            int y = mCollapsedSize;
210            canvas.drawLine(0, y, getWidth(), y, mDebugPaint);
211            y = (int) (getLayoutHeight() - mBottomStackPeekSize
212                    - mBottomStackSlowDownHeight);
213            canvas.drawLine(0, y, getWidth(), y, mDebugPaint);
214            y = (int) (getLayoutHeight() - mBottomStackPeekSize);
215            canvas.drawLine(0, y, getWidth(), y, mDebugPaint);
216            y = (int) getLayoutHeight();
217            canvas.drawLine(0, y, getWidth(), y, mDebugPaint);
218            y = getHeight() - getEmptyBottomMargin();
219            canvas.drawLine(0, y, getWidth(), y, mDebugPaint);
220        }
221    }
222
223    private void initView(Context context) {
224        mScroller = new OverScroller(getContext());
225        setFocusable(true);
226        setDescendantFocusability(FOCUS_AFTER_DESCENDANTS);
227        setClipChildren(false);
228        final ViewConfiguration configuration = ViewConfiguration.get(context);
229        mTouchSlop = configuration.getScaledTouchSlop();
230        mMinimumVelocity = configuration.getScaledMinimumFlingVelocity();
231        mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
232        mOverflingDistance = configuration.getScaledOverflingDistance();
233        float densityScale = getResources().getDisplayMetrics().density;
234        float pagingTouchSlop = ViewConfiguration.get(getContext()).getScaledPagingTouchSlop();
235        mSwipeHelper = new SwipeHelper(SwipeHelper.X, this, densityScale, pagingTouchSlop);
236        mSwipeHelper.setLongPressListener(mLongClickListener);
237
238        mSidePaddings = context.getResources()
239                .getDimensionPixelSize(R.dimen.notification_side_padding);
240        mCollapsedSize = context.getResources()
241                .getDimensionPixelSize(R.dimen.notification_min_height);
242        mBottomStackPeekSize = context.getResources()
243                .getDimensionPixelSize(R.dimen.bottom_stack_peek_amount);
244        mStackScrollAlgorithm = new StackScrollAlgorithm(context);
245        mStackScrollAlgorithm.setDimmed(mAmbientState.isDimmed());
246        mPaddingBetweenElementsDimmed = context.getResources()
247                .getDimensionPixelSize(R.dimen.notification_padding_dimmed);
248        mPaddingBetweenElementsNormal = context.getResources()
249                .getDimensionPixelSize(R.dimen.notification_padding);
250        updatePadding(mAmbientState.isDimmed());
251        int minHeight = getResources().getDimensionPixelSize(R.dimen.notification_min_height);
252        int maxHeight = getResources().getDimensionPixelSize(R.dimen.notification_max_height);
253        mExpandHelper = new ExpandHelper(getContext(), this,
254                minHeight, maxHeight);
255        mExpandHelper.setEventSource(this);
256        mExpandHelper.setScrollAdapter(this);
257        mMinTopOverScrollToEscape = getResources().getDimensionPixelSize(
258                R.dimen.min_top_overscroll_to_qs);
259        mNotificationTopPadding = getResources().getDimensionPixelSize(
260                R.dimen.notifications_top_padding);
261        mMinStackHeight = getResources().getDimensionPixelSize(R.dimen.collapsed_stack_height);
262    }
263
264    private void updatePadding(boolean dimmed) {
265        mPaddingBetweenElements = dimmed
266                ? mPaddingBetweenElementsDimmed
267                : mPaddingBetweenElementsNormal;
268        mBottomStackSlowDownHeight = mStackScrollAlgorithm.getBottomStackSlowDownLength();
269        updateContentHeight();
270        notifyHeightChangeListener(null);
271    }
272
273    private void notifyHeightChangeListener(ExpandableView view) {
274        if (mOnHeightChangedListener != null) {
275            mOnHeightChangedListener.onHeightChanged(view);
276        }
277    }
278
279    @Override
280    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
281        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
282        int mode = MeasureSpec.getMode(widthMeasureSpec);
283        int size = MeasureSpec.getSize(widthMeasureSpec);
284        int childMeasureSpec = MeasureSpec.makeMeasureSpec(size - 2 * mSidePaddings, mode);
285        measureChildren(childMeasureSpec, heightMeasureSpec);
286    }
287
288    @Override
289    protected void onLayout(boolean changed, int l, int t, int r, int b) {
290
291        // we layout all our children centered on the top
292        float centerX = getWidth() / 2.0f;
293        for (int i = 0; i < getChildCount(); i++) {
294            View child = getChildAt(i);
295            float width = child.getMeasuredWidth();
296            float height = child.getMeasuredHeight();
297            child.layout((int) (centerX - width / 2.0f),
298                    0,
299                    (int) (centerX + width / 2.0f),
300                    (int) height);
301        }
302        setMaxLayoutHeight(getHeight());
303        updateContentHeight();
304        updateScrollPositionIfNecessary();
305        requestChildrenUpdate();
306    }
307
308    public void updateSpeedBumpIndex(int newIndex) {
309        int currentIndex = indexOfChild(mSpeedBumpView);
310
311        // If we are currently layouted before the new speed bump index, we have to decrease it.
312        boolean validIndex = newIndex > 0;
313        if (newIndex > getChildCount() - 1) {
314            validIndex = false;
315            newIndex = -1;
316        }
317        if (validIndex && currentIndex != newIndex) {
318            changeViewPosition(mSpeedBumpView, newIndex);
319        }
320        updateSpeedBump(validIndex);
321        mAmbientState.setSpeedBumpIndex(newIndex);
322    }
323
324    public void setChildLocationsChangedListener(OnChildLocationsChangedListener listener) {
325        mListener = listener;
326    }
327
328    /**
329     * Returns the location the given child is currently rendered at.
330     *
331     * @param child the child to get the location for
332     * @return one of {@link ViewState}'s <code>LOCATION_*</code> constants
333     */
334    public int getChildLocation(View child) {
335        ViewState childViewState = mCurrentStackScrollState.getViewStateForView(child);
336        if (childViewState == null) {
337            return ViewState.LOCATION_UNKNOWN;
338        }
339        return childViewState.location;
340    }
341
342    private void setMaxLayoutHeight(int maxLayoutHeight) {
343        mMaxLayoutHeight = maxLayoutHeight;
344        updateAlgorithmHeightAndPadding();
345    }
346
347    private void updateAlgorithmHeightAndPadding() {
348        mStackScrollAlgorithm.setLayoutHeight(getLayoutHeight());
349        mStackScrollAlgorithm.setTopPadding(mTopPadding);
350    }
351
352    /**
353     * @return whether the height of the layout needs to be adapted, in order to ensure that the
354     *         last child is not in the bottom stack.
355     */
356    private boolean needsHeightAdaption() {
357        return getNotGoneChildCount() > 1;
358    }
359
360    /**
361     * Updates the children views according to the stack scroll algorithm. Call this whenever
362     * modifications to {@link #mOwnScrollY} are performed to reflect it in the view layout.
363     */
364    private void updateChildren() {
365        mAmbientState.setScrollY(mOwnScrollY);
366        mStackScrollAlgorithm.getStackScrollState(mAmbientState, mCurrentStackScrollState);
367        if (!isCurrentlyAnimating() && !mNeedsAnimation) {
368            applyCurrentState();
369        } else {
370            startAnimationToState();
371        }
372    }
373
374    private void requestChildrenUpdate() {
375        if (!mChildrenUpdateRequested) {
376            getViewTreeObserver().addOnPreDrawListener(mChildrenUpdater);
377            mChildrenUpdateRequested = true;
378            invalidate();
379        }
380    }
381
382    private boolean isCurrentlyAnimating() {
383        return mStateAnimator.isRunning();
384    }
385
386    private void updateScrollPositionIfNecessary() {
387        int scrollRange = getScrollRange();
388        if (scrollRange < mOwnScrollY) {
389            mOwnScrollY = scrollRange;
390        }
391    }
392
393    public int getTopPadding() {
394        return mTopPadding;
395    }
396
397    private void setTopPadding(int topPadding, boolean animate) {
398        if (mTopPadding != topPadding) {
399            mTopPadding = topPadding;
400            updateAlgorithmHeightAndPadding();
401            updateContentHeight();
402            if (animate && mAnimationsEnabled && mIsExpanded) {
403                mTopPaddingNeedsAnimation = true;
404                mNeedsAnimation =  true;
405            }
406            requestChildrenUpdate();
407            notifyHeightChangeListener(null);
408        }
409    }
410
411    /**
412     * Update the height of the stack to a new height.
413     *
414     * @param height the new height of the stack
415     */
416    public void setStackHeight(float height) {
417        setIsExpanded(height > 0.0f);
418        int newStackHeight = (int) height;
419        int itemHeight = getItemHeight();
420        int bottomStackPeekSize = mBottomStackPeekSize;
421        int minStackHeight = itemHeight + bottomStackPeekSize;
422        int stackHeight;
423        if (newStackHeight - mTopPadding >= minStackHeight || getNotGoneChildCount() == 0) {
424            setTranslationY(0);
425            stackHeight = newStackHeight;
426        } else {
427
428            // We did not reach the position yet where we actually start growing,
429            // so we translate the stack upwards.
430            int translationY = (newStackHeight - minStackHeight);
431            // A slight parallax effect is introduced in order for the stack to catch up with
432            // the top card.
433            float partiallyThere = (float) (newStackHeight - mTopPadding) / minStackHeight;
434            partiallyThere = Math.max(0, partiallyThere);
435            translationY += (1 - partiallyThere) * bottomStackPeekSize;
436            setTranslationY(translationY - mTopPadding);
437            stackHeight = (int) (height - (translationY - mTopPadding));
438        }
439        if (stackHeight != mCurrentStackHeight) {
440            mCurrentStackHeight = stackHeight;
441            updateAlgorithmHeightAndPadding();
442            requestChildrenUpdate();
443        }
444    }
445
446    /**
447     * Get the current height of the view. This is at most the msize of the view given by a the
448     * layout but it can also be made smaller by setting {@link #mCurrentStackHeight}
449     *
450     * @return either the layout height or the externally defined height, whichever is smaller
451     */
452    private int getLayoutHeight() {
453        return Math.min(mMaxLayoutHeight, mCurrentStackHeight);
454    }
455
456    public int getItemHeight() {
457        return mCollapsedSize;
458    }
459
460    public int getBottomStackPeekSize() {
461        return mBottomStackPeekSize;
462    }
463
464    public void setLongPressListener(View.OnLongClickListener listener) {
465        mSwipeHelper.setLongPressListener(listener);
466        mLongClickListener = listener;
467    }
468
469    public void onChildDismissed(View v) {
470        if (DEBUG) Log.v(TAG, "onChildDismissed: " + v);
471        final View veto = v.findViewById(R.id.veto);
472        if (veto != null && veto.getVisibility() != View.GONE) {
473            veto.performClick();
474        }
475        setSwipingInProgress(false);
476        if (mDragAnimPendingChildren.contains(v)) {
477            // We start the swipe and finish it in the same frame, we don't want any animation
478            // for the drag
479            mDragAnimPendingChildren.remove(v);
480        }
481        mSwipedOutViews.add(v);
482        mAmbientState.onDragFinished(v);
483    }
484
485    @Override
486    public void onChildSnappedBack(View animView) {
487        mAmbientState.onDragFinished(animView);
488        if (!mDragAnimPendingChildren.contains(animView)) {
489            if (mAnimationsEnabled) {
490                mSnappedBackChildren.add(animView);
491                mNeedsAnimation = true;
492            }
493            requestChildrenUpdate();
494        } else {
495            // We start the swipe and snap back in the same frame, we don't want any animation
496            mDragAnimPendingChildren.remove(animView);
497        }
498    }
499
500    @Override
501    public boolean updateSwipeProgress(View animView, boolean dismissable, float swipeProgress) {
502        return false;
503    }
504
505    public void onBeginDrag(View v) {
506        setSwipingInProgress(true);
507        mAmbientState.onBeginDrag(v);
508        if (mAnimationsEnabled) {
509            mDragAnimPendingChildren.add(v);
510            mNeedsAnimation = true;
511        }
512        requestChildrenUpdate();
513    }
514
515    public void onDragCancelled(View v) {
516        setSwipingInProgress(false);
517    }
518
519    public View getChildAtPosition(MotionEvent ev) {
520        return getChildAtPosition(ev.getX(), ev.getY());
521    }
522
523    public ExpandableView getChildAtRawPosition(float touchX, float touchY) {
524        int[] location = new int[2];
525        getLocationOnScreen(location);
526        return getChildAtPosition(touchX - location[0], touchY - location[1]);
527    }
528
529    public ExpandableView getChildAtPosition(float touchX, float touchY) {
530        // find the view under the pointer, accounting for GONE views
531        final int count = getChildCount();
532        for (int childIdx = 0; childIdx < count; childIdx++) {
533            ExpandableView slidingChild = (ExpandableView) getChildAt(childIdx);
534            if (slidingChild.getVisibility() == GONE) {
535                continue;
536            }
537            float childTop = slidingChild.getTranslationY();
538            float top = childTop + slidingChild.getClipTopAmount();
539            float bottom = childTop + slidingChild.getActualHeight();
540            int left = slidingChild.getLeft();
541            int right = slidingChild.getRight();
542
543            if (touchY >= top && touchY <= bottom && touchX >= left && touchX <= right) {
544                return slidingChild;
545            }
546        }
547        return null;
548    }
549
550    public boolean canChildBeExpanded(View v) {
551        return v instanceof ExpandableNotificationRow
552                && ((ExpandableNotificationRow) v).isExpandable();
553    }
554
555    public void setUserExpandedChild(View v, boolean userExpanded) {
556        if (v instanceof ExpandableNotificationRow) {
557            ((ExpandableNotificationRow) v).setUserExpanded(userExpanded);
558        }
559    }
560
561    public void setUserLockedChild(View v, boolean userLocked) {
562        if (v instanceof ExpandableNotificationRow) {
563            ((ExpandableNotificationRow) v).setUserLocked(userLocked);
564        }
565        removeLongPressCallback();
566        requestDisallowInterceptTouchEvent(true);
567    }
568
569    @Override
570    public void expansionStateChanged(boolean isExpanding) {
571        mExpandingNotification = isExpanding;
572        if (!mExpandedInThisMotion) {
573            mMaxScrollAfterExpand = mOwnScrollY;
574            mExpandedInThisMotion = true;
575        }
576    }
577
578    public void setScrollingEnabled(boolean enable) {
579        mScrollingEnabled = enable;
580    }
581
582    public void setExpandingEnabled(boolean enable) {
583        mExpandHelper.setEnabled(enable);
584    }
585
586    private boolean isScrollingEnabled() {
587        return mScrollingEnabled;
588    }
589
590    public View getChildContentView(View v) {
591        return v;
592    }
593
594    public boolean canChildBeDismissed(View v) {
595        final View veto = v.findViewById(R.id.veto);
596        return (veto != null && veto.getVisibility() != View.GONE);
597    }
598
599    private void setSwipingInProgress(boolean isSwiped) {
600        mSwipingInProgress = isSwiped;
601        if(isSwiped) {
602            requestDisallowInterceptTouchEvent(true);
603        }
604    }
605
606    @Override
607    protected void onConfigurationChanged(Configuration newConfig) {
608        super.onConfigurationChanged(newConfig);
609        float densityScale = getResources().getDisplayMetrics().density;
610        mSwipeHelper.setDensityScale(densityScale);
611        float pagingTouchSlop = ViewConfiguration.get(getContext()).getScaledPagingTouchSlop();
612        mSwipeHelper.setPagingTouchSlop(pagingTouchSlop);
613        initView(getContext());
614    }
615
616    public void dismissRowAnimated(View child, int vel) {
617        mSwipeHelper.dismissChild(child, vel);
618    }
619
620    @Override
621    public boolean onTouchEvent(MotionEvent ev) {
622        if (!isEnabled()) {
623            return false;
624        }
625        boolean isCancelOrUp = ev.getActionMasked() == MotionEvent.ACTION_CANCEL
626                || ev.getActionMasked()== MotionEvent.ACTION_UP;
627        boolean expandWantsIt = false;
628        if (!mSwipingInProgress && !mOnlyScrollingInThisMotion) {
629            if (isCancelOrUp) {
630                mExpandHelper.onlyObserveMovements(false);
631            }
632            boolean wasExpandingBefore = mExpandingNotification;
633            expandWantsIt = mExpandHelper.onTouchEvent(ev);
634            if (mExpandedInThisMotion && !mExpandingNotification && wasExpandingBefore) {
635                dispatchDownEventToScroller(ev);
636            }
637        }
638        boolean scrollerWantsIt = false;
639        if (!mSwipingInProgress && !mExpandingNotification) {
640            scrollerWantsIt = onScrollTouch(ev);
641        }
642        boolean horizontalSwipeWantsIt = false;
643        if (!mIsBeingDragged
644                && !mExpandingNotification
645                && !mExpandedInThisMotion
646                && !mOnlyScrollingInThisMotion) {
647            horizontalSwipeWantsIt = mSwipeHelper.onTouchEvent(ev);
648        }
649        return horizontalSwipeWantsIt || scrollerWantsIt || expandWantsIt || super.onTouchEvent(ev);
650    }
651
652    private void dispatchDownEventToScroller(MotionEvent ev) {
653        MotionEvent downEvent = MotionEvent.obtain(ev);
654        downEvent.setAction(MotionEvent.ACTION_DOWN);
655        onScrollTouch(downEvent);
656        downEvent.recycle();
657    }
658
659    private boolean onScrollTouch(MotionEvent ev) {
660        if (!isScrollingEnabled()) {
661            return false;
662        }
663        initVelocityTrackerIfNotExists();
664        mVelocityTracker.addMovement(ev);
665
666        final int action = ev.getAction();
667
668        switch (action & MotionEvent.ACTION_MASK) {
669            case MotionEvent.ACTION_DOWN: {
670                if (getChildCount() == 0 || !isInContentBounds(ev)) {
671                    return false;
672                }
673                boolean isBeingDragged = !mScroller.isFinished();
674                setIsBeingDragged(isBeingDragged);
675
676                /*
677                 * If being flinged and user touches, stop the fling. isFinished
678                 * will be false if being flinged.
679                 */
680                if (!mScroller.isFinished()) {
681                    mScroller.forceFinished(true);
682                }
683
684                // Remember where the motion event started
685                mLastMotionY = (int) ev.getY();
686                mDownX = (int) ev.getX();
687                mActivePointerId = ev.getPointerId(0);
688                break;
689            }
690            case MotionEvent.ACTION_MOVE:
691                final int activePointerIndex = ev.findPointerIndex(mActivePointerId);
692                if (activePointerIndex == -1) {
693                    Log.e(TAG, "Invalid pointerId=" + mActivePointerId + " in onTouchEvent");
694                    break;
695                }
696
697                final int y = (int) ev.getY(activePointerIndex);
698                final int x = (int) ev.getX(activePointerIndex);
699                int deltaY = mLastMotionY - y;
700                final int xDiff = Math.abs(x - mDownX);
701                final int yDiff = Math.abs(deltaY);
702                if (!mIsBeingDragged && yDiff > mTouchSlop && yDiff > xDiff) {
703                    setIsBeingDragged(true);
704                    if (deltaY > 0) {
705                        deltaY -= mTouchSlop;
706                    } else {
707                        deltaY += mTouchSlop;
708                    }
709                }
710                if (mIsBeingDragged) {
711                    // Scroll to follow the motion event
712                    mLastMotionY = y;
713                    int range = getScrollRange();
714                    if (mExpandedInThisMotion) {
715                        range = Math.min(range, mMaxScrollAfterExpand);
716                    }
717
718                    float scrollAmount;
719                    if (deltaY < 0) {
720                        scrollAmount = overScrollDown(deltaY);
721                    } else {
722                        scrollAmount = overScrollUp(deltaY, range);
723                    }
724
725                    // Calling overScrollBy will call onOverScrolled, which
726                    // calls onScrollChanged if applicable.
727                    if (scrollAmount != 0.0f) {
728                        // The scrolling motion could not be compensated with the
729                        // existing overScroll, we have to scroll the view
730                        overScrollBy(0, (int) scrollAmount, 0, mOwnScrollY,
731                                0, range, 0, getHeight() / 2, true);
732                    }
733                }
734                break;
735            case MotionEvent.ACTION_UP:
736                if (mIsBeingDragged) {
737                    final VelocityTracker velocityTracker = mVelocityTracker;
738                    velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
739                    int initialVelocity = (int) velocityTracker.getYVelocity(mActivePointerId);
740
741                    if (shouldOverScrollFling(initialVelocity)) {
742                        onOverScrollFling(true, initialVelocity);
743                    } else {
744                        if (getChildCount() > 0) {
745                            if ((Math.abs(initialVelocity) > mMinimumVelocity)) {
746                                float currentOverScrollTop = getCurrentOverScrollAmount(true);
747                                if (currentOverScrollTop == 0.0f || initialVelocity > 0) {
748                                    fling(-initialVelocity);
749                                } else {
750                                    onOverScrollFling(false, initialVelocity);
751                                }
752                            } else {
753                                if (mScroller.springBack(mScrollX, mOwnScrollY, 0, 0, 0,
754                                        getScrollRange())) {
755                                    postInvalidateOnAnimation();
756                                }
757                            }
758                        }
759                    }
760
761                    mActivePointerId = INVALID_POINTER;
762                    endDrag();
763                }
764
765                break;
766            case MotionEvent.ACTION_CANCEL:
767                if (mIsBeingDragged && getChildCount() > 0) {
768                    if (mScroller.springBack(mScrollX, mOwnScrollY, 0, 0, 0, getScrollRange())) {
769                        postInvalidateOnAnimation();
770                    }
771                    mActivePointerId = INVALID_POINTER;
772                    endDrag();
773                }
774                break;
775            case MotionEvent.ACTION_POINTER_DOWN: {
776                final int index = ev.getActionIndex();
777                mLastMotionY = (int) ev.getY(index);
778                mDownX = (int) ev.getX(index);
779                mActivePointerId = ev.getPointerId(index);
780                break;
781            }
782            case MotionEvent.ACTION_POINTER_UP:
783                onSecondaryPointerUp(ev);
784                mLastMotionY = (int) ev.getY(ev.findPointerIndex(mActivePointerId));
785                mDownX = (int) ev.getX(ev.findPointerIndex(mActivePointerId));
786                break;
787        }
788        return true;
789    }
790
791    private void onOverScrollFling(boolean open, int initialVelocity) {
792        if (mOverscrollTopChangedListener != null) {
793            mOverscrollTopChangedListener.flingTopOverscroll(initialVelocity, open);
794        }
795        mDontReportNextOverScroll = true;
796        setOverScrollAmount(0.0f, true, false);
797    }
798
799    /**
800     * Perform a scroll upwards and adapt the overscroll amounts accordingly
801     *
802     * @param deltaY The amount to scroll upwards, has to be positive.
803     * @return The amount of scrolling to be performed by the scroller,
804     *         not handled by the overScroll amount.
805     */
806    private float overScrollUp(int deltaY, int range) {
807        deltaY = Math.max(deltaY, 0);
808        float currentTopAmount = getCurrentOverScrollAmount(true);
809        float newTopAmount = currentTopAmount - deltaY;
810        if (currentTopAmount > 0) {
811            setOverScrollAmount(newTopAmount, true /* onTop */,
812                    false /* animate */);
813        }
814        // Top overScroll might not grab all scrolling motion,
815        // we have to scroll as well.
816        float scrollAmount = newTopAmount < 0 ? -newTopAmount : 0.0f;
817        float newScrollY = mOwnScrollY + scrollAmount;
818        if (newScrollY > range) {
819            if (!mExpandedInThisMotion) {
820                float currentBottomPixels = getCurrentOverScrolledPixels(false);
821                // We overScroll on the top
822                setOverScrolledPixels(currentBottomPixels + newScrollY - range,
823                        false /* onTop */,
824                        false /* animate */);
825            }
826            mOwnScrollY = range;
827            scrollAmount = 0.0f;
828        }
829        return scrollAmount;
830    }
831
832    /**
833     * Perform a scroll downward and adapt the overscroll amounts accordingly
834     *
835     * @param deltaY The amount to scroll downwards, has to be negative.
836     * @return The amount of scrolling to be performed by the scroller,
837     *         not handled by the overScroll amount.
838     */
839    private float overScrollDown(int deltaY) {
840        deltaY = Math.min(deltaY, 0);
841        float currentBottomAmount = getCurrentOverScrollAmount(false);
842        float newBottomAmount = currentBottomAmount + deltaY;
843        if (currentBottomAmount > 0) {
844            setOverScrollAmount(newBottomAmount, false /* onTop */,
845                    false /* animate */);
846        }
847        // Bottom overScroll might not grab all scrolling motion,
848        // we have to scroll as well.
849        float scrollAmount = newBottomAmount < 0 ? newBottomAmount : 0.0f;
850        float newScrollY = mOwnScrollY + scrollAmount;
851        if (newScrollY < 0) {
852            float currentTopPixels = getCurrentOverScrolledPixels(true);
853            // We overScroll on the top
854            setOverScrolledPixels(currentTopPixels - newScrollY,
855                    true /* onTop */,
856                    false /* animate */);
857            mOwnScrollY = 0;
858            scrollAmount = 0.0f;
859        }
860        return scrollAmount;
861    }
862
863    private void onSecondaryPointerUp(MotionEvent ev) {
864        final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
865                MotionEvent.ACTION_POINTER_INDEX_SHIFT;
866        final int pointerId = ev.getPointerId(pointerIndex);
867        if (pointerId == mActivePointerId) {
868            // This was our active pointer going up. Choose a new
869            // active pointer and adjust accordingly.
870            // TODO: Make this decision more intelligent.
871            final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
872            mLastMotionY = (int) ev.getY(newPointerIndex);
873            mActivePointerId = ev.getPointerId(newPointerIndex);
874            if (mVelocityTracker != null) {
875                mVelocityTracker.clear();
876            }
877        }
878    }
879
880    private void initVelocityTrackerIfNotExists() {
881        if (mVelocityTracker == null) {
882            mVelocityTracker = VelocityTracker.obtain();
883        }
884    }
885
886    private void recycleVelocityTracker() {
887        if (mVelocityTracker != null) {
888            mVelocityTracker.recycle();
889            mVelocityTracker = null;
890        }
891    }
892
893    private void initOrResetVelocityTracker() {
894        if (mVelocityTracker == null) {
895            mVelocityTracker = VelocityTracker.obtain();
896        } else {
897            mVelocityTracker.clear();
898        }
899    }
900
901    @Override
902    public void computeScroll() {
903        if (mScroller.computeScrollOffset()) {
904            // This is called at drawing time by ViewGroup.
905            int oldX = mScrollX;
906            int oldY = mOwnScrollY;
907            int x = mScroller.getCurrX();
908            int y = mScroller.getCurrY();
909
910            if (oldX != x || oldY != y) {
911                final int range = getScrollRange();
912                if (y < 0 && oldY >= 0 || y > range && oldY <= range) {
913                    float currVelocity = mScroller.getCurrVelocity();
914                    if (currVelocity >= mMinimumVelocity) {
915                        mMaxOverScroll = Math.abs(currVelocity) / 1000 * mOverflingDistance;
916                    }
917                }
918
919                overScrollBy(x - oldX, y - oldY, oldX, oldY, 0, range,
920                        0, (int) (mMaxOverScroll), false);
921                onScrollChanged(mScrollX, mOwnScrollY, oldX, oldY);
922            }
923
924            // Keep on drawing until the animation has finished.
925            postInvalidateOnAnimation();
926        }
927    }
928
929    @Override
930    protected boolean overScrollBy(int deltaX, int deltaY,
931            int scrollX, int scrollY,
932            int scrollRangeX, int scrollRangeY,
933            int maxOverScrollX, int maxOverScrollY,
934            boolean isTouchEvent) {
935
936        int newScrollY = scrollY + deltaY;
937
938        final int top = -maxOverScrollY;
939        final int bottom = maxOverScrollY + scrollRangeY;
940
941        boolean clampedY = false;
942        if (newScrollY > bottom) {
943            newScrollY = bottom;
944            clampedY = true;
945        } else if (newScrollY < top) {
946            newScrollY = top;
947            clampedY = true;
948        }
949
950        onOverScrolled(0, newScrollY, false, clampedY);
951
952        return clampedY;
953    }
954
955    /**
956     * Set the amount of overScrolled pixels which will force the view to apply a rubber-banded
957     * overscroll effect based on numPixels. By default this will also cancel animations on the
958     * same overScroll edge.
959     *
960     * @param numPixels The amount of pixels to overScroll by. These will be scaled according to
961     *                  the rubber-banding logic.
962     * @param onTop Should the effect be applied on top of the scroller.
963     * @param animate Should an animation be performed.
964     */
965    public void setOverScrolledPixels(float numPixels, boolean onTop, boolean animate) {
966        setOverScrollAmount(numPixels * getRubberBandFactor(onTop), onTop, animate, true);
967    }
968
969    /**
970     * Set the effective overScroll amount which will be directly reflected in the layout.
971     * By default this will also cancel animations on the same overScroll edge.
972     *
973     * @param amount The amount to overScroll by.
974     * @param onTop Should the effect be applied on top of the scroller.
975     * @param animate Should an animation be performed.
976     */
977    public void setOverScrollAmount(float amount, boolean onTop, boolean animate) {
978        setOverScrollAmount(amount, onTop, animate, true);
979    }
980
981    /**
982     * Set the effective overScroll amount which will be directly reflected in the layout.
983     *
984     * @param amount The amount to overScroll by.
985     * @param onTop Should the effect be applied on top of the scroller.
986     * @param animate Should an animation be performed.
987     * @param cancelAnimators Should running animations be cancelled.
988     */
989    public void setOverScrollAmount(float amount, boolean onTop, boolean animate,
990            boolean cancelAnimators) {
991        if (cancelAnimators) {
992            mStateAnimator.cancelOverScrollAnimators(onTop);
993        }
994        setOverScrollAmountInternal(amount, onTop, animate);
995    }
996
997    private void setOverScrollAmountInternal(float amount, boolean onTop, boolean animate) {
998        amount = Math.max(0, amount);
999        if (animate) {
1000            mStateAnimator.animateOverScrollToAmount(amount, onTop);
1001        } else {
1002            setOverScrolledPixels(amount / getRubberBandFactor(onTop), onTop);
1003            mAmbientState.setOverScrollAmount(amount, onTop);
1004            if (onTop) {
1005                notifyOverscrollTopListener(amount);
1006            }
1007            requestChildrenUpdate();
1008        }
1009    }
1010
1011    private void notifyOverscrollTopListener(float amount) {
1012        mExpandHelper.onlyObserveMovements(amount > 1.0f);
1013        if (mDontReportNextOverScroll) {
1014            mDontReportNextOverScroll = false;
1015            return;
1016        }
1017        if (mOverscrollTopChangedListener != null) {
1018            mOverscrollTopChangedListener.onOverscrollTopChanged(amount);
1019        }
1020    }
1021
1022    public void setOverscrollTopChangedListener(
1023            OnOverscrollTopChangedListener overscrollTopChangedListener) {
1024        mOverscrollTopChangedListener = overscrollTopChangedListener;
1025    }
1026
1027    public float getCurrentOverScrollAmount(boolean top) {
1028        return mAmbientState.getOverScrollAmount(top);
1029    }
1030
1031    public float getCurrentOverScrolledPixels(boolean top) {
1032        return top? mOverScrolledTopPixels : mOverScrolledBottomPixels;
1033    }
1034
1035    private void setOverScrolledPixels(float amount, boolean onTop) {
1036        if (onTop) {
1037            mOverScrolledTopPixels = amount;
1038        } else {
1039            mOverScrolledBottomPixels = amount;
1040        }
1041    }
1042
1043    private void customScrollTo(int y) {
1044        mOwnScrollY = y;
1045        updateChildren();
1046    }
1047
1048    @Override
1049    protected void onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY) {
1050        // Treat animating scrolls differently; see #computeScroll() for why.
1051        if (!mScroller.isFinished()) {
1052            final int oldX = mScrollX;
1053            final int oldY = mOwnScrollY;
1054            mScrollX = scrollX;
1055            mOwnScrollY = scrollY;
1056            if (clampedY) {
1057                springBack();
1058            } else {
1059                onScrollChanged(mScrollX, mOwnScrollY, oldX, oldY);
1060                invalidateParentIfNeeded();
1061                updateChildren();
1062                float overScrollTop = getCurrentOverScrollAmount(true);
1063                if (mOwnScrollY < 0) {
1064                    notifyOverscrollTopListener(-mOwnScrollY);
1065                } else {
1066                    notifyOverscrollTopListener(overScrollTop);
1067                }
1068            }
1069        } else {
1070            customScrollTo(scrollY);
1071            scrollTo(scrollX, mScrollY);
1072        }
1073    }
1074
1075    private void springBack() {
1076        int scrollRange = getScrollRange();
1077        boolean overScrolledTop = mOwnScrollY <= 0;
1078        boolean overScrolledBottom = mOwnScrollY >= scrollRange;
1079        if (overScrolledTop || overScrolledBottom) {
1080            boolean onTop;
1081            float newAmount;
1082            if (overScrolledTop) {
1083                onTop = true;
1084                newAmount = -mOwnScrollY;
1085                mOwnScrollY = 0;
1086                mDontReportNextOverScroll = true;
1087            } else {
1088                onTop = false;
1089                newAmount = mOwnScrollY - scrollRange;
1090                mOwnScrollY = scrollRange;
1091            }
1092            setOverScrollAmount(newAmount, onTop, false);
1093            setOverScrollAmount(0.0f, onTop, true);
1094            mScroller.forceFinished(true);
1095        }
1096    }
1097
1098    private int getScrollRange() {
1099        int scrollRange = 0;
1100        ExpandableView firstChild = (ExpandableView) getFirstChildNotGone();
1101        if (firstChild != null) {
1102            int contentHeight = getContentHeight();
1103            int firstChildMaxExpandHeight = getMaxExpandHeight(firstChild);
1104            scrollRange = Math.max(0, contentHeight - mMaxLayoutHeight + mBottomStackPeekSize
1105                    + mBottomStackSlowDownHeight);
1106            if (scrollRange > 0) {
1107                View lastChild = getLastChildNotGone();
1108                // We want to at least be able collapse the first item and not ending in a weird
1109                // end state.
1110                scrollRange = Math.max(scrollRange, firstChildMaxExpandHeight - mCollapsedSize);
1111            }
1112        }
1113        return scrollRange;
1114    }
1115
1116    /**
1117     * @return the first child which has visibility unequal to GONE
1118     */
1119    private View getFirstChildNotGone() {
1120        int childCount = getChildCount();
1121        for (int i = 0; i < childCount; i++) {
1122            View child = getChildAt(i);
1123            if (child.getVisibility() != View.GONE) {
1124                return child;
1125            }
1126        }
1127        return null;
1128    }
1129
1130    /**
1131     * @return The first child which has visibility unequal to GONE which is currently below the
1132     *         given translationY or equal to it.
1133     */
1134    private View getFirstChildBelowTranlsationY(float translationY) {
1135        int childCount = getChildCount();
1136        for (int i = 0; i < childCount; i++) {
1137            View child = getChildAt(i);
1138            if (child.getVisibility() != View.GONE && child.getTranslationY() >= translationY) {
1139                return child;
1140            }
1141        }
1142        return null;
1143    }
1144
1145    /**
1146     * @return the last child which has visibility unequal to GONE
1147     */
1148    public View getLastChildNotGone() {
1149        int childCount = getChildCount();
1150        for (int i = childCount - 1; i >= 0; i--) {
1151            View child = getChildAt(i);
1152            if (child.getVisibility() != View.GONE) {
1153                return child;
1154            }
1155        }
1156        return null;
1157    }
1158
1159    /**
1160     * @return the number of children which have visibility unequal to GONE
1161     */
1162    public int getNotGoneChildCount() {
1163        int childCount = getChildCount();
1164        int count = 0;
1165        for (int i = 0; i < childCount; i++) {
1166            View child = getChildAt(i);
1167            if (child.getVisibility() != View.GONE) {
1168                count++;
1169            }
1170        }
1171        return count;
1172    }
1173
1174    private int getMaxExpandHeight(View view) {
1175        if (view instanceof ExpandableNotificationRow) {
1176            ExpandableNotificationRow row = (ExpandableNotificationRow) view;
1177            return row.getIntrinsicHeight();
1178        }
1179        return view.getHeight();
1180    }
1181
1182    private int getContentHeight() {
1183        return mContentHeight;
1184    }
1185
1186    private void updateContentHeight() {
1187        int height = 0;
1188        for (int i = 0; i < getChildCount(); i++) {
1189            View child = getChildAt(i);
1190            if (child.getVisibility() != View.GONE) {
1191                if (height != 0) {
1192                    // add the padding before this element
1193                    height += mPaddingBetweenElements;
1194                }
1195                if (child instanceof ExpandableNotificationRow) {
1196                    ExpandableNotificationRow row = (ExpandableNotificationRow) child;
1197                    height += row.getIntrinsicHeight();
1198                } else if (child instanceof ExpandableView) {
1199                    ExpandableView expandableView = (ExpandableView) child;
1200                    height += expandableView.getActualHeight();
1201                }
1202            }
1203        }
1204        mContentHeight = height + mTopPadding;
1205    }
1206
1207    /**
1208     * Fling the scroll view
1209     *
1210     * @param velocityY The initial velocity in the Y direction. Positive
1211     *                  numbers mean that the finger/cursor is moving down the screen,
1212     *                  which means we want to scroll towards the top.
1213     */
1214    private void fling(int velocityY) {
1215        if (getChildCount() > 0) {
1216            int scrollRange = getScrollRange();
1217
1218            float topAmount = getCurrentOverScrollAmount(true);
1219            float bottomAmount = getCurrentOverScrollAmount(false);
1220            if (velocityY < 0 && topAmount > 0) {
1221                mOwnScrollY -= (int) topAmount;
1222                mDontReportNextOverScroll = true;
1223                setOverScrollAmount(0, true, false);
1224                mMaxOverScroll = Math.abs(velocityY) / 1000f * getRubberBandFactor(true /* onTop */)
1225                        * mOverflingDistance + topAmount;
1226            } else if (velocityY > 0 && bottomAmount > 0) {
1227                mOwnScrollY += bottomAmount;
1228                setOverScrollAmount(0, false, false);
1229                mMaxOverScroll = Math.abs(velocityY) / 1000f
1230                        * getRubberBandFactor(false /* onTop */) * mOverflingDistance
1231                        +  bottomAmount;
1232            } else {
1233                // it will be set once we reach the boundary
1234                mMaxOverScroll = 0.0f;
1235            }
1236            mScroller.fling(mScrollX, mOwnScrollY, 1, velocityY, 0, 0, 0,
1237                    Math.max(0, scrollRange), 0, Integer.MAX_VALUE / 2);
1238
1239            postInvalidateOnAnimation();
1240        }
1241    }
1242
1243    /**
1244     * @return Whether a fling performed on the top overscroll edge lead to the expanded
1245     * overScroll view (i.e QS).
1246     */
1247    private boolean shouldOverScrollFling(int initialVelocity) {
1248        float topOverScroll = getCurrentOverScrollAmount(true);
1249        return mScrolledToTopOnFirstDown
1250                && !mExpandedInThisMotion
1251                && topOverScroll > mMinTopOverScrollToEscape
1252                && initialVelocity > 0;
1253    }
1254
1255    public void updateTopPadding(float qsHeight, int scrollY, boolean animate) {
1256        float start = qsHeight - scrollY + mNotificationTopPadding;
1257        float stackHeight = getHeight() - start;
1258        if (stackHeight <= mMinStackHeight) {
1259            float overflow = mMinStackHeight - stackHeight;
1260            stackHeight = mMinStackHeight;
1261            start = getHeight() - stackHeight;
1262            setTranslationY(overflow);
1263        } else {
1264            setTranslationY(0);
1265        }
1266        setTopPadding(clampPadding((int) start), animate);
1267    }
1268
1269    public int getPeekHeight() {
1270        return mIntrinsicPadding + mCollapsedSize + mBottomStackPeekSize;
1271    }
1272
1273    private int clampPadding(int desiredPadding) {
1274        return Math.max(desiredPadding, mIntrinsicPadding);
1275    }
1276
1277    private float getRubberBandFactor(boolean onTop) {
1278        if (!onTop) {
1279            return RUBBER_BAND_FACTOR_NORMAL;
1280        }
1281        if (mExpandedInThisMotion) {
1282            return RUBBER_BAND_FACTOR_AFTER_EXPAND;
1283        } else if (mIsExpansionChanging) {
1284            return RUBBER_BAND_FACTOR_ON_PANEL_EXPAND;
1285        } else if (mScrolledToTopOnFirstDown) {
1286            return 1.0f;
1287        }
1288        return RUBBER_BAND_FACTOR_NORMAL;
1289    }
1290
1291    private void endDrag() {
1292        setIsBeingDragged(false);
1293
1294        recycleVelocityTracker();
1295
1296        if (getCurrentOverScrollAmount(true /* onTop */) > 0) {
1297            setOverScrollAmount(0, true /* onTop */, true /* animate */);
1298        }
1299        if (getCurrentOverScrollAmount(false /* onTop */) > 0) {
1300            setOverScrollAmount(0, false /* onTop */, true /* animate */);
1301        }
1302    }
1303
1304    @Override
1305    public boolean onInterceptTouchEvent(MotionEvent ev) {
1306        initDownStates(ev);
1307        boolean expandWantsIt = false;
1308        if (!mSwipingInProgress && !mOnlyScrollingInThisMotion) {
1309            expandWantsIt = mExpandHelper.onInterceptTouchEvent(ev);
1310        }
1311        boolean scrollWantsIt = false;
1312        if (!mSwipingInProgress && !mExpandingNotification) {
1313            scrollWantsIt = onInterceptTouchEventScroll(ev);
1314        }
1315        boolean swipeWantsIt = false;
1316        if (!mIsBeingDragged
1317                && !mExpandingNotification
1318                && !mExpandedInThisMotion
1319                && !mOnlyScrollingInThisMotion) {
1320            swipeWantsIt = mSwipeHelper.onInterceptTouchEvent(ev);
1321        }
1322        return swipeWantsIt || scrollWantsIt || expandWantsIt || super.onInterceptTouchEvent(ev);
1323    }
1324
1325    private void initDownStates(MotionEvent ev) {
1326        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
1327            mExpandedInThisMotion = false;
1328            mOnlyScrollingInThisMotion = !mScroller.isFinished();
1329        }
1330    }
1331
1332    @Override
1333    protected void onViewRemoved(View child) {
1334        super.onViewRemoved(child);
1335        mStackScrollAlgorithm.notifyChildrenChanged(this);
1336        if (mChangePositionInProgress) {
1337            // This is only a position change, don't do anything special
1338            return;
1339        }
1340        ((ExpandableView) child).setOnHeightChangedListener(null);
1341        mCurrentStackScrollState.removeViewStateForView(child);
1342        updateScrollStateForRemovedChild(child);
1343        boolean animationGenerated = generateRemoveAnimation(child);
1344        if (animationGenerated && !mSwipedOutViews.contains(child)) {
1345            // Add this view to an overlay in order to ensure that it will still be temporary
1346            // drawn when removed
1347            getOverlay().add(child);
1348        }
1349    }
1350
1351    /**
1352     * Generate a remove animation for a child view.
1353     *
1354     * @param child The view to generate the remove animation for.
1355     * @return Whether an animation was generated.
1356     */
1357    private boolean generateRemoveAnimation(View child) {
1358        if (mIsExpanded && mAnimationsEnabled) {
1359            if (!mChildrenToAddAnimated.contains(child)) {
1360                // Generate Animations
1361                mChildrenToRemoveAnimated.add(child);
1362                mNeedsAnimation = true;
1363                return true;
1364            } else {
1365                mChildrenToAddAnimated.remove(child);
1366                return false;
1367            }
1368        }
1369        return false;
1370    }
1371
1372    /**
1373     * Updates the scroll position when a child was removed
1374     *
1375     * @param removedChild the removed child
1376     */
1377    private void updateScrollStateForRemovedChild(View removedChild) {
1378        int startingPosition = getPositionInLinearLayout(removedChild);
1379        int childHeight = removedChild.getHeight() + mPaddingBetweenElements;
1380        int endPosition = startingPosition + childHeight;
1381        if (endPosition <= mOwnScrollY) {
1382            // This child is fully scrolled of the top, so we have to deduct its height from the
1383            // scrollPosition
1384            mOwnScrollY -= childHeight;
1385        } else if (startingPosition < mOwnScrollY) {
1386            // This child is currently being scrolled into, set the scroll position to the start of
1387            // this child
1388            mOwnScrollY = startingPosition;
1389        }
1390    }
1391
1392    private int getPositionInLinearLayout(View requestedChild) {
1393        int position = 0;
1394        for (int i = 0; i < getChildCount(); i++) {
1395            View child = getChildAt(i);
1396            if (child == requestedChild) {
1397                return position;
1398            }
1399            if (child.getVisibility() != View.GONE) {
1400                position += child.getHeight();
1401                if (i < getChildCount()-1) {
1402                    position += mPaddingBetweenElements;
1403                }
1404            }
1405        }
1406        return 0;
1407    }
1408
1409    @Override
1410    protected void onViewAdded(View child) {
1411        super.onViewAdded(child);
1412        mStackScrollAlgorithm.notifyChildrenChanged(this);
1413        ((ExpandableView) child).setOnHeightChangedListener(this);
1414        generateAddAnimation(child);
1415    }
1416
1417    public void setAnimationsEnabled(boolean animationsEnabled) {
1418        mAnimationsEnabled = animationsEnabled;
1419    }
1420
1421    public boolean isAddOrRemoveAnimationPending() {
1422        return mNeedsAnimation
1423                && (!mChildrenToAddAnimated.isEmpty() || !mChildrenToRemoveAnimated.isEmpty());
1424    }
1425    /**
1426     * Generate an animation for an added child view.
1427     *
1428     * @param child The view to be added.
1429     */
1430    public void generateAddAnimation(View child) {
1431        if (mIsExpanded && mAnimationsEnabled && !mChangePositionInProgress) {
1432            // Generate Animations
1433            mChildrenToAddAnimated.add(child);
1434            mNeedsAnimation = true;
1435        }
1436    }
1437
1438    /**
1439     * Change the position of child to a new location
1440     *
1441     * @param child the view to change the position for
1442     * @param newIndex the new index
1443     */
1444    public void changeViewPosition(View child, int newIndex) {
1445        if (child != null && child.getParent() == this) {
1446            mChangePositionInProgress = true;
1447            removeView(child);
1448            addView(child, newIndex);
1449            mChangePositionInProgress = false;
1450            if (mIsExpanded && mAnimationsEnabled) {
1451                mChildrenChangingPositions.add(child);
1452                mNeedsAnimation = true;
1453            }
1454        }
1455    }
1456
1457    private void startAnimationToState() {
1458        if (mNeedsAnimation) {
1459            generateChildHierarchyEvents();
1460            mNeedsAnimation = false;
1461        }
1462        if (!mAnimationEvents.isEmpty() || isCurrentlyAnimating()) {
1463            mStateAnimator.startAnimationForEvents(mAnimationEvents, mCurrentStackScrollState);
1464            mAnimationEvents.clear();
1465        } else {
1466            applyCurrentState();
1467        }
1468    }
1469
1470    private void generateChildHierarchyEvents() {
1471        generateChildRemovalEvents();
1472        generateChildAdditionEvents();
1473        generatePositionChangeEvents();
1474        generateSnapBackEvents();
1475        generateDragEvents();
1476        generateTopPaddingEvent();
1477        generateActivateEvent();
1478        generateDimmedEvent();
1479        generateDarkEvent();
1480        mNeedsAnimation = false;
1481    }
1482
1483    private void generateSnapBackEvents() {
1484        for (View child : mSnappedBackChildren) {
1485            mAnimationEvents.add(new AnimationEvent(child,
1486                    AnimationEvent.ANIMATION_TYPE_SNAP_BACK));
1487        }
1488        mSnappedBackChildren.clear();
1489    }
1490
1491    private void generateDragEvents() {
1492        for (View child : mDragAnimPendingChildren) {
1493            mAnimationEvents.add(new AnimationEvent(child,
1494                    AnimationEvent.ANIMATION_TYPE_START_DRAG));
1495        }
1496        mDragAnimPendingChildren.clear();
1497    }
1498
1499    private void generateChildRemovalEvents() {
1500        for (View child : mChildrenToRemoveAnimated) {
1501            boolean childWasSwipedOut = mSwipedOutViews.contains(child);
1502            int animationType = childWasSwipedOut
1503                    ? AnimationEvent.ANIMATION_TYPE_REMOVE_SWIPED_OUT
1504                    : AnimationEvent.ANIMATION_TYPE_REMOVE;
1505            AnimationEvent event = new AnimationEvent(child, animationType);
1506
1507            // we need to know the view after this one
1508            event.viewAfterChangingView = getFirstChildBelowTranlsationY(child.getTranslationY());
1509            mAnimationEvents.add(event);
1510        }
1511        mSwipedOutViews.clear();
1512        mChildrenToRemoveAnimated.clear();
1513    }
1514
1515    private void generatePositionChangeEvents() {
1516        for (View child : mChildrenChangingPositions) {
1517            mAnimationEvents.add(new AnimationEvent(child,
1518                    AnimationEvent.ANIMATION_TYPE_CHANGE_POSITION));
1519        }
1520        mChildrenChangingPositions.clear();
1521    }
1522
1523    private void generateChildAdditionEvents() {
1524        for (View child : mChildrenToAddAnimated) {
1525            mAnimationEvents.add(new AnimationEvent(child,
1526                    AnimationEvent.ANIMATION_TYPE_ADD));
1527        }
1528        mChildrenToAddAnimated.clear();
1529    }
1530
1531    private void generateTopPaddingEvent() {
1532        if (mTopPaddingNeedsAnimation) {
1533            mAnimationEvents.add(
1534                    new AnimationEvent(null, AnimationEvent.ANIMATION_TYPE_TOP_PADDING_CHANGED));
1535        }
1536        mTopPaddingNeedsAnimation = false;
1537    }
1538
1539    private void generateActivateEvent() {
1540        if (mActivateNeedsAnimation) {
1541            mAnimationEvents.add(
1542                    new AnimationEvent(null, AnimationEvent.ANIMATION_TYPE_ACTIVATED_CHILD));
1543        }
1544        mActivateNeedsAnimation = false;
1545    }
1546
1547    private void generateDimmedEvent() {
1548        if (mDimmedNeedsAnimation) {
1549            mAnimationEvents.add(
1550                    new AnimationEvent(null, AnimationEvent.ANIMATION_TYPE_DIMMED));
1551        }
1552        mDimmedNeedsAnimation = false;
1553    }
1554
1555    private void generateDarkEvent() {
1556        if (mDarkNeedsAnimation) {
1557            mAnimationEvents.add(
1558                    new AnimationEvent(null, AnimationEvent.ANIMATION_TYPE_DARK));
1559        }
1560        mDarkNeedsAnimation = false;
1561    }
1562
1563    private boolean onInterceptTouchEventScroll(MotionEvent ev) {
1564        if (!isScrollingEnabled()) {
1565            return false;
1566        }
1567        /*
1568         * This method JUST determines whether we want to intercept the motion.
1569         * If we return true, onMotionEvent will be called and we do the actual
1570         * scrolling there.
1571         */
1572
1573        /*
1574        * Shortcut the most recurring case: the user is in the dragging
1575        * state and he is moving his finger.  We want to intercept this
1576        * motion.
1577        */
1578        final int action = ev.getAction();
1579        if ((action == MotionEvent.ACTION_MOVE) && (mIsBeingDragged)) {
1580            return true;
1581        }
1582
1583        switch (action & MotionEvent.ACTION_MASK) {
1584            case MotionEvent.ACTION_MOVE: {
1585                /*
1586                 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
1587                 * whether the user has moved far enough from his original down touch.
1588                 */
1589
1590                /*
1591                * Locally do absolute value. mLastMotionY is set to the y value
1592                * of the down event.
1593                */
1594                final int activePointerId = mActivePointerId;
1595                if (activePointerId == INVALID_POINTER) {
1596                    // If we don't have a valid id, the touch down wasn't on content.
1597                    break;
1598                }
1599
1600                final int pointerIndex = ev.findPointerIndex(activePointerId);
1601                if (pointerIndex == -1) {
1602                    Log.e(TAG, "Invalid pointerId=" + activePointerId
1603                            + " in onInterceptTouchEvent");
1604                    break;
1605                }
1606
1607                final int y = (int) ev.getY(pointerIndex);
1608                final int x = (int) ev.getX(pointerIndex);
1609                final int yDiff = Math.abs(y - mLastMotionY);
1610                final int xDiff = Math.abs(x - mDownX);
1611                if (yDiff > mTouchSlop && yDiff > xDiff) {
1612                    setIsBeingDragged(true);
1613                    mLastMotionY = y;
1614                    mDownX = x;
1615                    initVelocityTrackerIfNotExists();
1616                    mVelocityTracker.addMovement(ev);
1617                }
1618                break;
1619            }
1620
1621            case MotionEvent.ACTION_DOWN: {
1622                final int y = (int) ev.getY();
1623                if (getChildAtPosition(ev.getX(), y) == null) {
1624                    setIsBeingDragged(false);
1625                    recycleVelocityTracker();
1626                    break;
1627                }
1628
1629                /*
1630                 * Remember location of down touch.
1631                 * ACTION_DOWN always refers to pointer index 0.
1632                 */
1633                mLastMotionY = y;
1634                mDownX = (int) ev.getX();
1635                mActivePointerId = ev.getPointerId(0);
1636                mScrolledToTopOnFirstDown = isScrolledToTop();
1637
1638                initOrResetVelocityTracker();
1639                mVelocityTracker.addMovement(ev);
1640                /*
1641                * If being flinged and user touches the screen, initiate drag;
1642                * otherwise don't.  mScroller.isFinished should be false when
1643                * being flinged.
1644                */
1645                boolean isBeingDragged = !mScroller.isFinished();
1646                setIsBeingDragged(isBeingDragged);
1647                break;
1648            }
1649
1650            case MotionEvent.ACTION_CANCEL:
1651            case MotionEvent.ACTION_UP:
1652                /* Release the drag */
1653                setIsBeingDragged(false);
1654                mActivePointerId = INVALID_POINTER;
1655                recycleVelocityTracker();
1656                if (mScroller.springBack(mScrollX, mOwnScrollY, 0, 0, 0, getScrollRange())) {
1657                    postInvalidateOnAnimation();
1658                }
1659                break;
1660            case MotionEvent.ACTION_POINTER_UP:
1661                onSecondaryPointerUp(ev);
1662                break;
1663        }
1664
1665        /*
1666        * The only time we want to intercept motion events is if we are in the
1667        * drag mode.
1668        */
1669        return mIsBeingDragged;
1670    }
1671
1672    /**
1673     * @return Whether the specified motion event is actually happening over the content.
1674     */
1675    private boolean isInContentBounds(MotionEvent event) {
1676        return event.getY() < getHeight() - getEmptyBottomMargin();
1677    }
1678
1679    private void setIsBeingDragged(boolean isDragged) {
1680        mIsBeingDragged = isDragged;
1681        if (isDragged) {
1682            requestDisallowInterceptTouchEvent(true);
1683            removeLongPressCallback();
1684        }
1685    }
1686
1687    @Override
1688    public void onWindowFocusChanged(boolean hasWindowFocus) {
1689        super.onWindowFocusChanged(hasWindowFocus);
1690        if (!hasWindowFocus) {
1691            removeLongPressCallback();
1692        }
1693    }
1694
1695    public void removeLongPressCallback() {
1696        mSwipeHelper.removeLongPressCallback();
1697    }
1698
1699    @Override
1700    public boolean isScrolledToTop() {
1701        return mOwnScrollY == 0;
1702    }
1703
1704    @Override
1705    public boolean isScrolledToBottom() {
1706        return mOwnScrollY >= getScrollRange();
1707    }
1708
1709    @Override
1710    public View getHostView() {
1711        return this;
1712    }
1713
1714    public int getEmptyBottomMargin() {
1715        int emptyMargin = mMaxLayoutHeight - mContentHeight;
1716        if (needsHeightAdaption()) {
1717            emptyMargin = emptyMargin - mBottomStackSlowDownHeight - mBottomStackPeekSize;
1718        } else {
1719            emptyMargin = emptyMargin - mBottomStackPeekSize;
1720        }
1721        return Math.max(emptyMargin, 0);
1722    }
1723
1724    public void onExpansionStarted() {
1725        mIsExpansionChanging = true;
1726        mStackScrollAlgorithm.onExpansionStarted(mCurrentStackScrollState);
1727    }
1728
1729    public void onExpansionStopped() {
1730        mIsExpansionChanging = false;
1731        mStackScrollAlgorithm.onExpansionStopped();
1732    }
1733
1734    private void setIsExpanded(boolean isExpanded) {
1735        mIsExpanded = isExpanded;
1736        mStackScrollAlgorithm.setIsExpanded(isExpanded);
1737        if (!isExpanded) {
1738            mOwnScrollY = 0;
1739        }
1740    }
1741
1742    @Override
1743    public void onHeightChanged(ExpandableView view) {
1744        updateContentHeight();
1745        updateScrollPositionIfNecessary();
1746        notifyHeightChangeListener(view);
1747        requestChildrenUpdate();
1748    }
1749
1750    public void setOnHeightChangedListener(
1751            ExpandableView.OnHeightChangedListener mOnHeightChangedListener) {
1752        this.mOnHeightChangedListener = mOnHeightChangedListener;
1753    }
1754
1755    public void onChildAnimationFinished() {
1756        requestChildrenUpdate();
1757    }
1758
1759    /**
1760     * See {@link AmbientState#setDimmed}.
1761     */
1762    public void setDimmed(boolean dimmed, boolean animate) {
1763        mStackScrollAlgorithm.setDimmed(dimmed);
1764        mAmbientState.setDimmed(dimmed);
1765        updatePadding(dimmed);
1766        if (animate && mAnimationsEnabled) {
1767            mDimmedNeedsAnimation = true;
1768            mNeedsAnimation =  true;
1769        }
1770        requestChildrenUpdate();
1771    }
1772
1773    /**
1774     * See {@link AmbientState#setActivatedChild}.
1775     */
1776    public void setActivatedChild(ActivatableNotificationView activatedChild) {
1777        mAmbientState.setActivatedChild(activatedChild);
1778        if (mAnimationsEnabled) {
1779            mActivateNeedsAnimation = true;
1780            mNeedsAnimation =  true;
1781        }
1782        requestChildrenUpdate();
1783    }
1784
1785    public ActivatableNotificationView getActivatedChild() {
1786        return mAmbientState.getActivatedChild();
1787    }
1788
1789    private void applyCurrentState() {
1790        mCurrentStackScrollState.apply();
1791        if (mListener != null) {
1792            mListener.onChildLocationsChanged(this);
1793        }
1794    }
1795
1796    public void setSpeedBumpView(SpeedBumpView speedBumpView) {
1797        mSpeedBumpView = speedBumpView;
1798        addView(speedBumpView);
1799    }
1800
1801    private void updateSpeedBump(boolean visible) {
1802        boolean notGoneBefore = mSpeedBumpView.getVisibility() != GONE;
1803        if (visible != notGoneBefore) {
1804            int newVisibility = visible ? VISIBLE : GONE;
1805            mSpeedBumpView.setVisibility(newVisibility);
1806            if (visible) {
1807                // Make invisible to ensure that the appear animation is played.
1808                mSpeedBumpView.setInvisible();
1809                if (!mIsExpansionChanging) {
1810                    generateAddAnimation(mSpeedBumpView);
1811                }
1812            } else {
1813                mSpeedBumpView.performVisibilityAnimation(false);
1814                generateRemoveAnimation(mSpeedBumpView);
1815            }
1816        }
1817    }
1818
1819    public void goToFullShade() {
1820        updateSpeedBump(true);
1821    }
1822
1823    public void cancelExpandHelper() {
1824        mExpandHelper.cancel();
1825    }
1826
1827    public void setIntrinsicPadding(int intrinsicPadding) {
1828        mIntrinsicPadding = intrinsicPadding;
1829    }
1830
1831    /**
1832     * @return the y position of the first notification
1833     */
1834    public float getNotificationsTopY() {
1835        return mTopPadding + getTranslationY();
1836    }
1837
1838    public void setTouchEnabled(boolean touchEnabled) {
1839        mTouchEnabled = touchEnabled;
1840    }
1841
1842    @Override
1843    public boolean dispatchTouchEvent(MotionEvent ev) {
1844        if (!mTouchEnabled) {
1845            return false;
1846        }
1847        return super.dispatchTouchEvent(ev);
1848    }
1849
1850    @Override
1851    public boolean shouldDelayChildPressedState() {
1852        return true;
1853    }
1854
1855    public void setScrimAlpha(float progress) {
1856        mAmbientState.setScrimAmount(progress);
1857        requestChildrenUpdate();
1858    }
1859
1860    /**
1861     * See {@link AmbientState#setDark}.
1862     */
1863    public void setDark(boolean dark, boolean animate) {
1864        mAmbientState.setDark(dark);
1865        if (animate && mAnimationsEnabled) {
1866            mDarkNeedsAnimation = true;
1867            mNeedsAnimation =  true;
1868        }
1869        requestChildrenUpdate();
1870    }
1871
1872    /**
1873     * A listener that is notified when some child locations might have changed.
1874     */
1875    public interface OnChildLocationsChangedListener {
1876        public void onChildLocationsChanged(NotificationStackScrollLayout stackScrollLayout);
1877    }
1878
1879    /**
1880     * A listener that gets notified when the overscroll at the top has changed.
1881     */
1882    public interface OnOverscrollTopChangedListener {
1883        public void onOverscrollTopChanged(float amount);
1884
1885        /**
1886         * Notify a listener that the scroller wants to escape from the scrolling motion and
1887         * start a fling animation to the expanded or collapsed overscroll view (e.g expand the QS)
1888         *
1889         * @param velocity The velocity that the Scroller had when over flinging
1890         * @param open Should the fling open or close the overscroll view.
1891         */
1892        public void flingTopOverscroll(float velocity, boolean open);
1893    }
1894
1895    static class AnimationEvent {
1896
1897        static AnimationFilter[] FILTERS = new AnimationFilter[] {
1898
1899                // ANIMATION_TYPE_ADD
1900                new AnimationFilter()
1901                        .animateAlpha()
1902                        .animateHeight()
1903                        .animateTopInset()
1904                        .animateY()
1905                        .animateZ()
1906                        .hasDelays(),
1907
1908                // ANIMATION_TYPE_REMOVE
1909                new AnimationFilter()
1910                        .animateAlpha()
1911                        .animateHeight()
1912                        .animateTopInset()
1913                        .animateY()
1914                        .animateZ()
1915                        .hasDelays(),
1916
1917                // ANIMATION_TYPE_REMOVE_SWIPED_OUT
1918                new AnimationFilter()
1919                        .animateAlpha()
1920                        .animateHeight()
1921                        .animateTopInset()
1922                        .animateY()
1923                        .animateZ()
1924                        .hasDelays(),
1925
1926                // ANIMATION_TYPE_TOP_PADDING_CHANGED
1927                new AnimationFilter()
1928                        .animateAlpha()
1929                        .animateHeight()
1930                        .animateTopInset()
1931                        .animateY()
1932                        .animateDimmed()
1933                        .animateScale()
1934                        .animateZ(),
1935
1936                // ANIMATION_TYPE_START_DRAG
1937                new AnimationFilter()
1938                        .animateAlpha(),
1939
1940                // ANIMATION_TYPE_SNAP_BACK
1941                new AnimationFilter()
1942                        .animateAlpha(),
1943
1944                // ANIMATION_TYPE_ACTIVATED_CHILD
1945                new AnimationFilter()
1946                        .animateScale()
1947                        .animateAlpha(),
1948
1949                // ANIMATION_TYPE_DIMMED
1950                new AnimationFilter()
1951                        .animateY()
1952                        .animateScale()
1953                        .animateDimmed(),
1954
1955                // ANIMATION_TYPE_CHANGE_POSITION
1956                new AnimationFilter()
1957                        .animateAlpha()
1958                        .animateHeight()
1959                        .animateTopInset()
1960                        .animateY()
1961                        .animateZ(),
1962
1963                // ANIMATION_TYPE_DARK
1964                new AnimationFilter()
1965                        .animateDark(),
1966        };
1967
1968        static int[] LENGTHS = new int[] {
1969
1970                // ANIMATION_TYPE_ADD
1971                StackStateAnimator.ANIMATION_DURATION_APPEAR_DISAPPEAR,
1972
1973                // ANIMATION_TYPE_REMOVE
1974                StackStateAnimator.ANIMATION_DURATION_APPEAR_DISAPPEAR,
1975
1976                // ANIMATION_TYPE_REMOVE_SWIPED_OUT
1977                StackStateAnimator.ANIMATION_DURATION_STANDARD,
1978
1979                // ANIMATION_TYPE_TOP_PADDING_CHANGED
1980                StackStateAnimator.ANIMATION_DURATION_STANDARD,
1981
1982                // ANIMATION_TYPE_START_DRAG
1983                StackStateAnimator.ANIMATION_DURATION_STANDARD,
1984
1985                // ANIMATION_TYPE_SNAP_BACK
1986                StackStateAnimator.ANIMATION_DURATION_STANDARD,
1987
1988                // ANIMATION_TYPE_ACTIVATED_CHILD
1989                StackStateAnimator.ANIMATION_DURATION_DIMMED_ACTIVATED,
1990
1991                // ANIMATION_TYPE_DIMMED
1992                StackStateAnimator.ANIMATION_DURATION_DIMMED_ACTIVATED,
1993
1994                // ANIMATION_TYPE_CHANGE_POSITION
1995                StackStateAnimator.ANIMATION_DURATION_STANDARD,
1996
1997                // ANIMATION_TYPE_DARK
1998                StackStateAnimator.ANIMATION_DURATION_STANDARD,
1999        };
2000
2001        static final int ANIMATION_TYPE_ADD = 0;
2002        static final int ANIMATION_TYPE_REMOVE = 1;
2003        static final int ANIMATION_TYPE_REMOVE_SWIPED_OUT = 2;
2004        static final int ANIMATION_TYPE_TOP_PADDING_CHANGED = 3;
2005        static final int ANIMATION_TYPE_START_DRAG = 4;
2006        static final int ANIMATION_TYPE_SNAP_BACK = 5;
2007        static final int ANIMATION_TYPE_ACTIVATED_CHILD = 6;
2008        static final int ANIMATION_TYPE_DIMMED = 7;
2009        static final int ANIMATION_TYPE_CHANGE_POSITION = 8;
2010        static final int ANIMATION_TYPE_DARK = 9;
2011
2012        final long eventStartTime;
2013        final View changingView;
2014        final int animationType;
2015        final AnimationFilter filter;
2016        final long length;
2017        View viewAfterChangingView;
2018
2019        AnimationEvent(View view, int type) {
2020            eventStartTime = AnimationUtils.currentAnimationTimeMillis();
2021            changingView = view;
2022            animationType = type;
2023            filter = FILTERS[type];
2024            length = LENGTHS[type];
2025        }
2026
2027        /**
2028         * Combines the length of several animation events into a single value.
2029         *
2030         * @param events The events of the lengths to combine.
2031         * @return The combined length. This is just the maximum of all length.
2032         */
2033        static long combineLength(ArrayList<AnimationEvent> events) {
2034            long length = 0;
2035            int size = events.size();
2036            for (int i = 0; i < size; i++) {
2037                length = Math.max(length, events.get(i).length);
2038            }
2039            return length;
2040        }
2041    }
2042
2043}
2044