Example usage for android.animation AnimatorSet playTogether

List of usage examples for android.animation AnimatorSet playTogether

Introduction

In this page you can find the example usage for android.animation AnimatorSet playTogether.

Prototype

public void playTogether(Collection<Animator> items) 

Source Link

Document

Sets up this AnimatorSet to play all of the supplied animations at the same time.

Usage

From source file:eu.davidea.flexibleadapter.AnimatorAdapter.java

protected void animateView(final RecyclerView.ViewHolder holder, final int position) {
    //FIXME: first completed visible item on rotation gets high delay

    //      if (DEBUG)
    //         Log.v(TAG, "shouldAnimate=" + shouldAnimate
    //               + " isFastScroll=" + isFastScroll
    //               + " isNotified=" + mAnimatorNotifierObserver.isPositionNotified()
    //               + " isReverseEnabled=" + isReverseEnabled
    //               + " mLastAnimatedPosition=" + mLastAnimatedPosition
    //               + (!isReverseEnabled ? " Pos>AniPos=" + (position > mLastAnimatedPosition) : "")
    //         );

    if (holder instanceof FlexibleViewHolder && shouldAnimate && !isFastScroll
            && !mAnimatorNotifierObserver.isPositionNotified()
            && (isReverseEnabled || position > mLastAnimatedPosition
                    || (position == 0 && mRecyclerView.getChildCount() == 0))) {

        //Cancel animation is necessary when fling
        int hashCode = holder.itemView.hashCode();
        cancelExistingAnimation(hashCode);

        //User animators
        List<Animator> animators = new ArrayList<>();
        FlexibleViewHolder flexibleViewHolder = (FlexibleViewHolder) holder;
        flexibleViewHolder.scrollAnimators(animators, position, position > mLastAnimatedPosition);

        //Execute the animations together
        AnimatorSet set = new AnimatorSet();
        set.playTogether(animators);
        set.setInterpolator(mInterpolator);
        set.setDuration(mDuration);//from w w w  .  j  a va  2  s. co  m
        set.addListener(new HelperAnimatorListener(hashCode));
        if (mEntryStep) {
            //Stop stepDelay when screen is filled
            set.setStartDelay(calculateAnimationDelay2(position));
        }
        set.start();
        mAnimators.put(hashCode, set);
        if (DEBUG)
            Log.d(TAG, "Started Animation on position " + position);

        //Animate only during initial loading?
        if (onlyEntryAnimation && position >= mMaxChildViews) {
            shouldAnimate = false;
        }
    }

    mAnimatorNotifierObserver.clearNotified();
    mLastAnimatedPosition = position;
}

From source file:com.flexible.flexibleadapter.AnimatorAdapter.java

/**
 * Animates the view based on the custom animator list built with {@link #getAnimators(View, int, boolean)}.
 *
 * @since 5.0.0-b1/*www .java  2 s . c om*/
 * @deprecated New system in place. Implement {@link FlexibleViewHolder#scrollAnimators(List, int, boolean)}
 * and add new animator(s) to the list of {@code animators}.
 */
@Deprecated
public final void animateView(final View itemView, int position) {
    //      if (DEBUG)
    //         Log.v(TAG, "shouldAnimate=" + shouldAnimate
    //               + " isFastScroll=" + isFastScroll
    //               + " isNotified=" + mAnimatorNotifierObserver.isPositionNotified()
    //               + " isReverseEnabled=" + isReverseEnabled
    //               + " mLastAnimatedPosition=" + mLastAnimatedPosition
    //               + (!isReverseEnabled ? " Pos>AniPos=" + (position > mLastAnimatedPosition) : "")
    //         );

    if (shouldAnimate && !isFastScroll && !mAnimatorNotifierObserver.isPositionNotified() && (isReverseEnabled
            || position > mLastAnimatedPosition || (position == 0 && mRecyclerView.getChildCount() == 0))) {

        //Cancel animation is necessary when fling
        cancelExistingAnimation(itemView.hashCode());

        //Retrieve user animators
        List<Animator> animators = getAnimators(itemView, position, position > mLastAnimatedPosition);

        //Add Alpha animator
        ViewCompat.setAlpha(itemView, 0);
        animators.add(ObjectAnimator.ofFloat(itemView, "alpha", 0f, 1f));
        Log.w(TAG, "Started Deprecated Animation on position " + position);

        //Execute the animations
        AnimatorSet set = new AnimatorSet();
        set.playTogether(animators);
        set.setInterpolator(mInterpolator);
        set.setDuration(mDuration);
        set.addListener(new HelperAnimatorListener(itemView.hashCode()));
        if (mEntryStep) {
            set.setStartDelay(calculateAnimationDelay(position));
        }
        set.start();
        mAnimators.put(itemView.hashCode(), set);

        //Animate only during initial loading?
        if (onlyEntryAnimation && mLastAnimatedPosition >= mMaxChildViews) {
            shouldAnimate = false;
        }
    }

    mAnimatorNotifierObserver.clearNotified();
    mLastAnimatedPosition = position;
}

From source file:arun.com.chromer.webheads.WebHeadService.java

private void updateWebHeadColors(@ColorInt int webHeadColor) {
    final AnimatorSet animatorSet = new AnimatorSet();
    final List<Animator> animators = new LinkedList<>();
    for (WebHead webhead : webHeads.values()) {
        animators.add(webhead.getRevealAnimator(webHeadColor));
    }/*  w w w  . j a v a2s .  co  m*/
    animatorSet.playTogether(animators);
    animatorSet.start();
}

From source file:com.flexible.flexibleadapter.AnimatorAdapter.java

/**
 * Performs checks to scroll animate the itemView and in case, it animates the view.
 * <p><b>Note:</b> If you have to change at runtime the LayoutManager <i>and</i> add
 * Scrollable Headers too, consider to add them in post, using a {@code delay >= 0},
 * otherwise scroll animations on all items will not start correctly.</p>
 *
 * @param holder   the ViewHolder just bound
 * @param position the current item position
 *///ww  w  .  j a v a 2 s . co  m
@SuppressWarnings("ConstantConditions")
protected final void animateView(final RecyclerView.ViewHolder holder, final int position) {
    if (mRecyclerView == null)
        return;

    // Use always the max child count reached
    if (mMaxChildViews < mRecyclerView.getChildCount()) {
        mMaxChildViews = mRecyclerView.getChildCount();
    }
    // Animate only during initial loading?
    if (onlyEntryAnimation && mLastAnimatedPosition >= mMaxChildViews) {
        shouldAnimate = false;
    }
    int lastVisiblePosition = Utils.findLastVisibleItemPosition(mRecyclerView.getLayoutManager());
    //      if (DEBUG) {
    //         Log.v(TAG, "shouldAnimate=" + shouldAnimate
    //               + " isFastScroll=" + isFastScroll
    //               + " isNotified=" + mAnimatorNotifierObserver.isPositionNotified()
    //               + " isReverseEnabled=" + isReverseEnabled
    //               + " mLastAnimatedPosition=" + mLastAnimatedPosition
    //               + (!isReverseEnabled ? " Pos>LasVisPos=" + (position > lastVisiblePosition) : "")
    //               + " mMaxChildViews=" + mMaxChildViews
    //         );
    //      }
    if (holder instanceof FlexibleViewHolder && shouldAnimate && !isFastScroll
            && !mAnimatorNotifierObserver.isPositionNotified()
            && (position > lastVisiblePosition || isReverseEnabled || isScrollableHeaderOrFooter(position)
                    || (position == 0 && mMaxChildViews == 0))) {

        // Cancel animation is necessary when fling
        int hashCode = holder.itemView.hashCode();
        cancelExistingAnimation(hashCode);

        // User animators
        List<Animator> animators = new ArrayList<>();
        FlexibleViewHolder flexibleViewHolder = (FlexibleViewHolder) holder;
        flexibleViewHolder.scrollAnimators(animators, position, position >= lastVisiblePosition);

        // Execute the animations together
        AnimatorSet set = new AnimatorSet();
        set.playTogether(animators);
        set.setInterpolator(mInterpolator);
        // Single view duration
        long duration = mDuration;
        for (Animator animator : animators) {
            if (animator.getDuration() != DEFAULT_DURATION) {
                duration = animator.getDuration();
            }
        }
        //Log.v(TAG, "duration=" + duration);
        set.setDuration(duration);
        set.addListener(new HelperAnimatorListener(hashCode));
        if (mEntryStep) {
            // Stop stepDelay when screen is filled
            set.setStartDelay(calculateAnimationDelay(position));
        }
        set.start();
        mAnimators.put(hashCode, set);
        if (DEBUG)
            Log.v(TAG, "animateView    Scroll animation on position " + position);
    }
    mAnimatorNotifierObserver.clearNotified();
    // Update last animated position
    mLastAnimatedPosition = position;
}

From source file:org.telegram.ui.Components.StickersAlert.java

private void hidePreview() {
    AnimatorSet animatorSet = new AnimatorSet();
    animatorSet.playTogether(ObjectAnimator.ofFloat(stickerPreviewLayout, "alpha", 0.0f));
    animatorSet.setDuration(200);//from   w ww . j  av a  2  s.  c o  m
    animatorSet.addListener(new AnimatorListenerAdapterProxy() {
        @Override
        public void onAnimationEnd(Animator animation) {
            stickerPreviewLayout.setVisibility(View.GONE);
        }
    });
    animatorSet.start();
}

From source file:graphic.expand_graphic.ExpandingListView.java

/**
 * This method collapses the view that was clicked and animates all the
 * views around it to close around the collapsing view. There are several
 * steps required to do this which are outlined below.
 * <p/>//from   w  w  w.  j a  v a 2s . c  o m
 * 1. Update the layout parameters of the view clicked so as to minimize its
 * height to the original collapsed (default) state. 2. After invoking a
 * layout, the listview will shift all the cells so as to display them most
 * efficiently. Therefore, during the first predraw pass, the listview must
 * be offset by some amount such that given the custom bound change upon
 * collapse, all the cells that need to be on the screen after the layout
 * are rendered by the listview. 3. On the second predraw pass, all the
 * items are first returned to their original location (before the first
 * layout). 4. The collapsing view's bounds are animated to what the final
 * values should be. 5. The bounds above the collapsing view are animated
 * downwards while the bounds below the collapsing view are animated
 * upwards. 6. The extra text is faded out as its contents become visible
 * throughout the animation process.
 */

private void collapseView(final View view) {

    /* Store the original top and bottom bounds of all the cells. */
    final int oldTop = view.getTop();
    final int oldBottom = view.getBottom();

    final HashMap<View, int[]> oldCoordinates = new HashMap<View, int[]>();

    int childCount = getChildCount();
    for (int i = 0; i < childCount; i++) {
        View v = getChildAt(i);
        ViewCompat.setHasTransientState(v, true);
        oldCoordinates.put(v, new int[] { v.getTop(), v.getBottom() });
    }

    /* Update the layout so the extra content becomes invisible. */
    view.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, viewObject.mCollapsedHeight));

    /* Add an onPreDraw listener. */
    final ViewTreeObserver observer = getViewTreeObserver();
    observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {

        @Override
        public boolean onPreDraw() {

            if (!mShouldRemoveObserver) {
                /*
                 * Same as for expandingView, the parameters for
                 * setSelectionFromTop must be determined such that the
                 * necessary cells of the ListView are rendered and added to
                 * it.
                 */
                mShouldRemoveObserver = true;

                int newTop = view.getTop();
                int newBottom = view.getBottom();

                int newHeight = newBottom - newTop;
                int oldHeight = oldBottom - oldTop;
                int deltaHeight = oldHeight - newHeight;

                mTranslate = getTopAndBottomTranslations(oldTop, oldBottom, deltaHeight, false);

                int currentTop = view.getTop();
                int futureTop = oldTop + mTranslate[0];

                int firstChildStartTop = getChildAt(0).getTop();
                int firstVisiblePosition = getFirstVisiblePosition();
                int deltaTop = currentTop - futureTop;

                int i;
                int childCount = getChildCount();
                for (i = 0; i < childCount; i++) {
                    View v = getChildAt(i);
                    int height = v.getBottom() - Math.max(0, v.getTop());
                    if (deltaTop - height > 0) {
                        firstVisiblePosition++;
                        deltaTop -= height;
                    } else {
                        break;
                    }
                }

                if (i > 0) {
                    firstChildStartTop = 0;
                }

                setSelectionFromTop(firstVisiblePosition, firstChildStartTop - deltaTop);

                requestLayout();

                return false;
            }

            mShouldRemoveObserver = false;
            observer.removeOnPreDrawListener(this);

            int yTranslateTop = mTranslate[0];
            int yTranslateBottom = mTranslate[1];

            int index = indexOfChild(view);
            int childCount = getChildCount();
            for (int i = 0; i < childCount; i++) {
                View v = getChildAt(i);
                int[] old = oldCoordinates.get(v);
                if (old != null) {
                    /*
                     * If the cell was present in the ListView before the
                     * collapse and after the collapse then the bounds are
                     * reset to their old values.
                     */
                    v.setTop(old[0]);
                    v.setBottom(old[1]);
                    ViewCompat.setHasTransientState(v, false);
                } else {
                    /*
                     * If the cell is present in the ListView after the
                     * collapse but not before the collapse then the bounds
                     * are calculated using the bottom and top translation
                     * of the collapsing cell.
                     */
                    int delta = i > index ? yTranslateBottom : -yTranslateTop;
                    v.setTop(v.getTop() + delta);
                    v.setBottom(v.getBottom() + delta);
                }
            }

            final View expandingLayout = view.findViewById(R.id.expanding_layout);

            /*
             * Animates all the cells present on the screen after the
             * collapse.
             */
            ArrayList<Animator> animations = new ArrayList<Animator>();
            for (int i = 0; i < childCount; i++) {
                View v = getChildAt(i);
                if (v != view) {
                    float diff = i > index ? -yTranslateBottom : yTranslateTop;
                    animations.add(getAnimation(v, diff, diff));
                }
            }

            /* Adds animation for collapsing the cell that was clicked. */
            animations.add(getAnimation(view, yTranslateTop, -yTranslateBottom));

            /* Adds an animation for fading out the extra content. */
            animations.add(ObjectAnimator.ofFloat(expandingLayout, View.ALPHA, 1, 0));

            /* Disabled the ListView for the duration of the animation. */
            setEnabled(false);
            setClickable(false);

            /*
             * Play all the animations created above together at the same
             * time.
             */
            AnimatorSet s = new AnimatorSet();
            s.playTogether(animations);
            s.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    expandingLayout.setVisibility(View.GONE);
                    view.setLayoutParams(
                            new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
                    viewObject.setExpanded(false);
                    setEnabled(true);
                    setClickable(true);
                    /*
                     * Note that alpha must be set back to 1 in case this
                     * view is reused by a cell that was expanded, but not
                     * yet collapsed, so its state should persist in an
                     * expanded state with the extra content visible.
                     */
                    expandingLayout.setAlpha(1);
                }
            });
            s.start();

            return true;
        }
    });
}

From source file:graphic.expand_graphic.ExpandingListView.java

/**
 * This method expands the view that was clicked and animates all the views
 * around it to make room for the expanding view. There are several steps
 * required to do this which are outlined below.
 * <p/>/*  w  ww  . j ava 2s .  co m*/
 * 1. Store the current top and bottom bounds of each visible item in the
 * listview. 2. Update the layout parameters of the selected view. In the
 * context of this method, the view should be originally collapsed and set
 * to some custom height. The layout parameters are updated so as to wrap
 * the content of the additional text that is to be displayed.
 * <p/>
 * After invoking a layout to take place, the listview will order all the
 * items such that there is space for each view. This layout will be
 * independent of what the bounds of the items were prior to the layout so
 * two pre-draw passes will be made. This is necessary because after the
 * layout takes place, some views that were visible before the layout may
 * now be off bounds but a reference to these views is required so the
 * animation completes as intended.
 * <p/>
 * 3. The first predraw pass will set the bounds of all the visible items to
 * their original location before the layout took place and then force
 * another layout. Since the bounds of the cells cannot be set directly, the
 * method setSelectionFromTop can be used to achieve a very similar effect.
 * 4. The expanding view's bounds are animated to what the final values
 * should be from the original bounds. 5. The bounds above the expanding
 * view are animated upwards while the bounds below the expanding view are
 * animated downwards. 6. The extra text is faded in as its contents become
 * visible throughout the animation process.
 * <p/>
 * It is important to note that the listview is disabled during the
 * animation because the scrolling behaviour is unpredictable if the bounds
 * of the items within the listview are not constant during the scroll.
 */

private void expandView(final View view) {

    /* Store the original top and bottom bounds of all the cells. */
    final int oldTop = view.getTop();
    final int oldBottom = view.getBottom();

    final HashMap<View, int[]> oldCoordinates = new HashMap<View, int[]>();

    int childCount = getChildCount();
    for (int i = 0; i < childCount; i++) {
        View v = getChildAt(i);
        ViewCompat.setHasTransientState(v, true);
        oldCoordinates.put(v, new int[] { v.getTop(), v.getBottom() });
    }

    /* Update the layout so the extra content becomes visible. */
    final View expandingLayout = view.findViewById(R.id.expanding_layout);
    expandingLayout.setVisibility(View.VISIBLE);

    /*
       * Add an onPreDraw Listener to the listview. onPreDraw will get invoked
     * after onLayout and onMeasure have run but before anything has been
     * drawn. This means that the final post layout properties for all the
     * items have already been determined, but still have not been rendered
     * onto the screen.
     */
    final ViewTreeObserver observer = getViewTreeObserver();
    observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {

        @Override
        public boolean onPreDraw() {
            /* Determine if this is the first or second pass. */
            if (!mShouldRemoveObserver) {
                mShouldRemoveObserver = true;

                /*
                 * Calculate what the parameters should be for
                 * setSelectionFromTop. The ListView must be offset in a
                 * way, such that after the animation takes place, all the
                 * cells that remain visible are rendered completely by the
                 * ListView.
                 */
                int newTop = view.getTop();
                int newBottom = view.getBottom();

                int newHeight = newBottom - newTop;
                int oldHeight = oldBottom - oldTop;
                int delta = newHeight - oldHeight;

                mTranslate = getTopAndBottomTranslations(oldTop, oldBottom, delta, true);

                int currentTop = view.getTop();
                int futureTop = oldTop - mTranslate[0];

                int firstChildStartTop = getChildAt(0).getTop();
                int firstVisiblePosition = getFirstVisiblePosition();
                int deltaTop = currentTop - futureTop;

                int i;
                int childCount = getChildCount();
                for (i = 0; i < childCount; i++) {
                    View v = getChildAt(i);
                    int height = v.getBottom() - Math.max(0, v.getTop());
                    if (deltaTop - height > 0) {
                        firstVisiblePosition++;
                        deltaTop -= height;
                    } else {
                        break;
                    }
                }

                if (i > 0) {
                    firstChildStartTop = 0;
                }

                setSelectionFromTop(firstVisiblePosition, firstChildStartTop - deltaTop);

                /*
                 * Request another layout to update the layout parameters of
                 * the cells.
                 */
                requestLayout();

                /*
                 * Return false such that the ListView does not redraw its
                 * contents on this layout but only updates all the
                 * parameters associated with its children.
                 */
                return false;
            }

            /*
             * Remove the predraw listener so this method does not keep
             * getting called.
             */
            mShouldRemoveObserver = false;
            observer.removeOnPreDrawListener(this);

            int yTranslateTop = mTranslate[0];
            int yTranslateBottom = mTranslate[1];

            ArrayList<Animator> animations = new ArrayList<Animator>();

            int index = indexOfChild(view);

            /*
             * Loop through all the views that were on the screen before the
             * cell was expanded. Some cells will still be children of the
             * ListView while others will not. The cells that remain
             * children of the ListView simply have their bounds animated
             * appropriately. The cells that are no longer children of the
             * ListView also have their bounds animated, but must also be
             * added to a list of views which will be drawn in dispatchDraw.
             */
            for (View v : oldCoordinates.keySet()) {
                int[] old = oldCoordinates.get(v);
                v.setTop(old[0]);
                v.setBottom(old[1]);
                if (v.getParent() == null) {
                    mViewsToDraw.add(v);
                    int delta = old[0] < oldTop ? -yTranslateTop : yTranslateBottom;
                    animations.add(getAnimation(v, delta, delta));
                } else {
                    int i = indexOfChild(v);
                    if (v != view) {
                        int delta = i > index ? yTranslateBottom : -yTranslateTop;
                        animations.add(getAnimation(v, delta, delta));
                    }
                    ViewCompat.setHasTransientState(v, false);
                }
            }

            /* Adds animation for expanding the cell that was clicked. */
            animations.add(getAnimation(view, -yTranslateTop, yTranslateBottom));

            /* Adds an animation for fading in the extra content. */
            animations.add(ObjectAnimator.ofFloat(view.findViewById(R.id.expanding_layout), View.ALPHA, 0, 1));

            /* Disabled the ListView for the duration of the animation. */
            setEnabled(false);
            setClickable(false);

            /*
             * Play all the animations created above together at the same
             * time.
             */
            AnimatorSet s = new AnimatorSet();
            s.playTogether(animations);
            s.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    viewObject.setExpanded(true);
                    setEnabled(true);
                    setClickable(true);
                    if (mViewsToDraw.size() > 0) {
                        for (View v : mViewsToDraw) {
                            ViewCompat.setHasTransientState(v, false);
                        }
                    }
                    mViewsToDraw.clear();
                }
            });
            s.start();
            return true;
        }
    });
}

From source file:com.tmall.wireless.tangram.ext.SwipeItemTouchListener.java

private void resetViews(RecyclerView recyclerView, final int swipingType, final boolean reachActionEdge,
        final int direction) {
    int contentWidth = recyclerView.getWidth();
    AnimatorSet animatorSet = new AnimatorSet();
    List<Animator> list = new ArrayList<>();
    String translation = "translationX";
    if (swipingType == SWIPING_VER) {
        translation = "translationY";
    }//  w w w.  j a  v a2  s .  c  o m
    for (View view : mChildList) {
        ObjectAnimator animator;
        if (reachActionEdge) {
            animator = ObjectAnimator.ofFloat(view, translation, contentWidth * direction)
                    .setDuration(ANIMATE_DURATION);
            animator.setInterpolator(new AccelerateInterpolator());
        } else {
            animator = ObjectAnimator.ofFloat(view, translation, 0).setDuration(ANIMATE_DURATION);
            animator.setInterpolator(new DecelerateInterpolator());
        }
        list.add(animator);
    }
    animatorSet.playTogether(list);
    animatorSet.addListener(new Animator.AnimatorListener() {
        @Override
        public void onAnimationStart(Animator animation) {

        }

        @Override
        public void onAnimationEnd(Animator animation) {
            if (swipingType == SWIPING_HOR && reachActionEdge) {
                if (mSwipeCardRef != null && mSwipeCardRef.get() != null) {
                    SwipeCard swipeCard = mSwipeCardRef.get();
                    swipeCard.switchTo(swipeCard.getCurrentIndex() - direction);
                }
            }
            mChildList.clear();
        }

        @Override
        public void onAnimationCancel(Animator animation) {

        }

        @Override
        public void onAnimationRepeat(Animator animation) {

        }
    });
    animatorSet.start();

    if (swipingType == SWIPING_VER) {
        if (pullFromEndListener != null) {
            if (mDistanceY < 0 && (mDistanceY < -pullFromEndListener.getPullEdge())) {
                pullFromEndListener.onAction();
            } else {
                pullFromEndListener.onReset();
            }
        }
    }

    swipeType = SWIPING_NONE;
}

From source file:com.android.tv.settings.dialog.DialogFragment.java

private Animator createDummyAnimator(final View v, ArrayList<Animator> animators) {
    final AnimatorSet animatorSet = new AnimatorSet();
    animatorSet.playTogether(animators);
    return new UntargetableAnimatorSet(animatorSet);
}

From source file:org.telegram.ui.Components.StickersAlert.java

private void init(Context context) {
    shadowDrawable = context.getResources().getDrawable(R.drawable.sheet_shadow);

    containerView = new FrameLayout(context) {

        private int lastNotifyWidth;

        @Override//from   w ww .  j av a2s  .c om
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            if (ev.getAction() == MotionEvent.ACTION_DOWN && scrollOffsetY != 0 && ev.getY() < scrollOffsetY) {
                dismiss();
                return true;
            }
            return super.onInterceptTouchEvent(ev);
        }

        @Override
        public boolean onTouchEvent(MotionEvent e) {
            return !isDismissed() && super.onTouchEvent(e);
        }

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int height = MeasureSpec.getSize(heightMeasureSpec);
            if (Build.VERSION.SDK_INT >= 21) {
                height -= AndroidUtilities.statusBarHeight;
            }
            int contentSize;
            if (stickerSetCovereds != null) {
                contentSize = AndroidUtilities.dp(48 + 8) + AndroidUtilities.dp(60) * stickerSetCovereds.size()
                        + adapter.stickersRowCount * AndroidUtilities.dp(82);
            } else {
                contentSize = AndroidUtilities.dp(48 + 48) + Math.max(3,
                        (stickerSet != null ? (int) Math.ceil(stickerSet.documents.size() / 5.0f) : 0))
                        * AndroidUtilities.dp(82) + backgroundPaddingTop;
            }
            int padding = contentSize < (height / 5 * 3.2) ? 0 : (height / 5 * 2);
            if (padding != 0 && contentSize < height) {
                padding -= (height - contentSize);
            }
            if (padding == 0) {
                padding = backgroundPaddingTop;
            }
            if (stickerSetCovereds != null) {
                padding += AndroidUtilities.dp(8);
            }
            if (gridView.getPaddingTop() != padding) {
                ignoreLayout = true;
                gridView.setPadding(AndroidUtilities.dp(10), padding, AndroidUtilities.dp(10), 0);
                emptyView.setPadding(0, padding, 0, 0);
                ignoreLayout = false;
            }
            super.onMeasure(widthMeasureSpec,
                    MeasureSpec.makeMeasureSpec(Math.min(contentSize, height), MeasureSpec.EXACTLY));
        }

        @Override
        protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
            if (lastNotifyWidth != right - left) {
                lastNotifyWidth = right - left;
                if (adapter != null && stickerSetCovereds != null) {
                    adapter.notifyDataSetChanged();
                }
            }
            super.onLayout(changed, left, top, right, bottom);
            updateLayout();
        }

        @Override
        public void requestLayout() {
            if (ignoreLayout) {
                return;
            }
            super.requestLayout();
        }

        @Override
        protected void onDraw(Canvas canvas) {
            shadowDrawable.setBounds(0, scrollOffsetY - backgroundPaddingTop, getMeasuredWidth(),
                    getMeasuredHeight());
            shadowDrawable.draw(canvas);
        }
    };
    containerView.setWillNotDraw(false);
    containerView.setPadding(backgroundPaddingLeft, 0, backgroundPaddingLeft, 0);

    titleTextView = new TextView(context);
    titleTextView.setLines(1);
    titleTextView.setSingleLine(true);
    titleTextView.setTextColor(
            ContextCompat.getColor(context, R.color.primary_text) /*Theme.STICKERS_SHEET_TITLE_TEXT_COLOR*/);
    titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);
    titleTextView.setEllipsize(TextUtils.TruncateAt.MIDDLE);
    titleTextView.setPadding(AndroidUtilities.dp(18), 0, AndroidUtilities.dp(18), 0);
    titleTextView.setGravity(Gravity.CENTER_VERTICAL);
    titleTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    containerView.addView(titleTextView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 48));
    titleTextView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return true;
        }
    });

    shadow[0] = new View(context);
    shadow[0].setBackgroundResource(R.drawable.header_shadow);
    shadow[0].setAlpha(0.0f);
    shadow[0].setVisibility(View.INVISIBLE);
    shadow[0].setTag(1);
    containerView.addView(shadow[0],
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 3, Gravity.TOP | Gravity.LEFT, 0, 48, 0, 0));

    gridView = new RecyclerListView(context) {
        @Override
        public boolean onInterceptTouchEvent(MotionEvent event) {
            boolean result = StickerPreviewViewer.getInstance().onInterceptTouchEvent(event, gridView, 0);
            return super.onInterceptTouchEvent(event) || result;
        }

        @Override
        public void requestLayout() {
            if (ignoreLayout) {
                return;
            }
            super.requestLayout();
        }
    };
    gridView.setTag(14);
    gridView.setLayoutManager(layoutManager = new GridLayoutManager(getContext(), 5));
    layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
        @Override
        public int getSpanSize(int position) {
            if (stickerSetCovereds != null && adapter.cache.get(position) instanceof Integer
                    || position == adapter.totalItems) {
                return adapter.stickersPerRow;
            }
            return 1;
        }
    });
    gridView.setAdapter(adapter = new GridAdapter(context));
    gridView.setVerticalScrollBarEnabled(false);
    gridView.addItemDecoration(new RecyclerView.ItemDecoration() {
        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            outRect.left = 0;
            outRect.right = 0;
            outRect.bottom = 0;
            outRect.top = 0;
        }
    });
    gridView.setPadding(AndroidUtilities.dp(10), 0, AndroidUtilities.dp(10), 0);
    gridView.setClipToPadding(false);
    gridView.setEnabled(true);
    gridView.setGlowColor(0xfff5f6f7);
    gridView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return StickerPreviewViewer.getInstance().onTouch(event, gridView, 0, stickersOnItemClickListener);
        }
    });
    gridView.setOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            updateLayout();
        }
    });
    stickersOnItemClickListener = new RecyclerListView.OnItemClickListener() {
        @Override
        public void onItemClick(View view, int position) {
            if (stickerSetCovereds != null) {
                TLRPC.StickerSetCovered pack = adapter.positionsToSets.get(position);
                if (pack != null) {
                    dismiss();
                    TLRPC.TL_inputStickerSetID inputStickerSetID = new TLRPC.TL_inputStickerSetID();
                    inputStickerSetID.access_hash = pack.set.access_hash;
                    inputStickerSetID.id = pack.set.id;
                    StickersAlert alert = new StickersAlert(parentActivity, parentFragment, inputStickerSetID,
                            null, null);
                    alert.show();
                }
            } else {
                if (stickerSet == null || position < 0 || position >= stickerSet.documents.size()) {
                    return;
                }
                selectedSticker = stickerSet.documents.get(position);

                boolean set = false;
                for (int a = 0; a < selectedSticker.attributes.size(); a++) {
                    TLRPC.DocumentAttribute attribute = selectedSticker.attributes.get(a);
                    if (attribute instanceof TLRPC.TL_documentAttributeSticker) {
                        if (attribute.alt != null && attribute.alt.length() > 0) {
                            stickerEmojiTextView.setText(Emoji.replaceEmoji(attribute.alt,
                                    stickerEmojiTextView.getPaint().getFontMetricsInt(),
                                    AndroidUtilities.dp(30), false));
                            set = true;
                        }
                        break;
                    }
                }
                if (!set) {
                    stickerEmojiTextView
                            .setText(Emoji.replaceEmoji(StickersQuery.getEmojiForSticker(selectedSticker.id),
                                    stickerEmojiTextView.getPaint().getFontMetricsInt(),
                                    AndroidUtilities.dp(30), false));
                }

                stickerImageView.getImageReceiver().setImage(selectedSticker, null,
                        selectedSticker.thumb.location, null, "webp", true);
                FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) stickerPreviewLayout
                        .getLayoutParams();
                layoutParams.topMargin = scrollOffsetY;
                stickerPreviewLayout.setLayoutParams(layoutParams);
                stickerPreviewLayout.setVisibility(View.VISIBLE);
                AnimatorSet animatorSet = new AnimatorSet();
                animatorSet.playTogether(ObjectAnimator.ofFloat(stickerPreviewLayout, "alpha", 0.0f, 1.0f));
                animatorSet.setDuration(200);
                animatorSet.start();
            }
        }
    };
    gridView.setOnItemClickListener(stickersOnItemClickListener);
    containerView.addView(gridView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT, 0, 48, 0, 48));

    emptyView = new FrameLayout(context) {
        @Override
        public void requestLayout() {
            if (ignoreLayout) {
                return;
            }
            super.requestLayout();
        }
    };
    containerView.addView(emptyView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT, 0, 0, 0, 48));
    gridView.setEmptyView(emptyView);
    emptyView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return true;
        }
    });

    ProgressBar progressView = new ProgressBar(context);
    emptyView.addView(progressView,
            LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));

    shadow[1] = new View(context);
    shadow[1].setBackgroundResource(R.drawable.header_shadow_reverse);
    containerView.addView(shadow[1],
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 3, Gravity.BOTTOM | Gravity.LEFT, 0, 0, 0, 48));

    pickerBottomLayout = new PickerBottomLayout(context, false);
    containerView.addView(pickerBottomLayout,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.LEFT | Gravity.BOTTOM));
    pickerBottomLayout.cancelButton.setPadding(AndroidUtilities.dp(18), 0, AndroidUtilities.dp(18), 0);
    pickerBottomLayout.cancelButton.setTextColor(Theme.STICKERS_SHEET_CLOSE_TEXT_COLOR);
    pickerBottomLayout.cancelButton.setText(LocaleController.getString("Close", R.string.Close).toUpperCase());
    pickerBottomLayout.cancelButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            dismiss();
        }
    });
    pickerBottomLayout.doneButton.setPadding(AndroidUtilities.dp(18), 0, AndroidUtilities.dp(18), 0);
    pickerBottomLayout.doneButtonBadgeTextView.setBackgroundResource(R.drawable.stickercounter);

    stickerPreviewLayout = new FrameLayout(context);
    if ((context.getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_YES) != 0) {
        stickerPreviewLayout.setBackgroundColor(
                0x00ffffff & ContextCompat.getColor(context, R.color.card_background) | 0xdf000000);
    } else {
        stickerPreviewLayout.setBackgroundColor(0xdfffffff);
    }
    stickerPreviewLayout.setVisibility(View.GONE);
    stickerPreviewLayout.setSoundEffectsEnabled(false);
    containerView.addView(stickerPreviewLayout,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    stickerPreviewLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            hidePreview();
        }
    });

    ImageView closeButton = new ImageView(context);
    closeButton.setImageResource(R.drawable.delete_reply);
    closeButton.setScaleType(ImageView.ScaleType.CENTER);
    if (Build.VERSION.SDK_INT >= 21) {
        closeButton.setBackgroundDrawable(Theme.createBarSelectorDrawable(Theme.INPUT_FIELD_SELECTOR_COLOR));
    }
    stickerPreviewLayout.addView(closeButton, LayoutHelper.createFrame(48, 48, Gravity.RIGHT | Gravity.TOP));
    closeButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            hidePreview();
        }
    });

    stickerImageView = new BackupImageView(context);
    stickerImageView.setAspectFit(true);
    stickerPreviewLayout.addView(stickerImageView);

    stickerEmojiTextView = new TextView(context);
    stickerEmojiTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 30);
    stickerEmojiTextView.setGravity(Gravity.BOTTOM | Gravity.RIGHT);
    stickerPreviewLayout.addView(stickerEmojiTextView);

    previewSendButton = new TextView(context);
    previewSendButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    previewSendButton.setTextColor(Theme.STICKERS_SHEET_SEND_TEXT_COLOR);
    previewSendButton.setGravity(Gravity.CENTER);
    previewSendButton.setBackgroundColor(ContextCompat.getColor(context, R.color.background));
    previewSendButton.setPadding(AndroidUtilities.dp(29), 0, AndroidUtilities.dp(29), 0);
    previewSendButton.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    stickerPreviewLayout.addView(previewSendButton,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.BOTTOM | Gravity.LEFT));
    previewSendButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            delegate.onStickerSelected(selectedSticker);
            dismiss();
        }
    });

    previewSendButtonShadow = new View(context);
    previewSendButtonShadow.setBackgroundResource(R.drawable.header_shadow_reverse);
    stickerPreviewLayout.addView(previewSendButtonShadow,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 3, Gravity.BOTTOM | Gravity.LEFT, 0, 0, 0, 48));
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.emojiDidLoaded);

    updateFields();
    updateSendButton();
    adapter.notifyDataSetChanged();
}