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:com.android.clear.reminder.ItemAnimator.java

@Override
public void runPendingAnimations() {
    final AnimatorSet removeAnimatorSet = new AnimatorSet();
    removeAnimatorSet.playTogether(mRemoveAnimatorsList);
    mRemoveAnimatorsList.clear();/*from   www .  j  a v  a  2 s .  com*/

    final AnimatorSet addAnimatorSet = new AnimatorSet();
    addAnimatorSet.playTogether(mAddAnimatorsList);
    mAddAnimatorsList.clear();

    final AnimatorSet changeAnimatorSet = new AnimatorSet();
    changeAnimatorSet.playTogether(mChangeAnimatorsList);
    mChangeAnimatorsList.clear();

    final AnimatorSet moveAnimatorSet = new AnimatorSet();
    moveAnimatorSet.playTogether(mMoveAnimatorsList);
    mMoveAnimatorsList.clear();

    final AnimatorSet pendingAnimatorSet = new AnimatorSet();
    pendingAnimatorSet.addListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animator) {
            animator.removeAllListeners();
            dispatchFinishedWhenDone();
        }
    });
    // Required order: removes, then changes & moves simultaneously, then additions. There are
    // redundant edges because changes or moves may be empty, causing the removes to incorrectly
    // play immediately.
    pendingAnimatorSet.play(removeAnimatorSet).before(changeAnimatorSet);
    pendingAnimatorSet.play(removeAnimatorSet).before(moveAnimatorSet);
    pendingAnimatorSet.play(changeAnimatorSet).with(moveAnimatorSet);
    pendingAnimatorSet.play(addAnimatorSet).after(changeAnimatorSet);
    pendingAnimatorSet.play(addAnimatorSet).after(moveAnimatorSet);
    pendingAnimatorSet.start();
}

From source file:me.hammarstrom.imagerecognition.activities.MainActivity.java

private void convertResponseToString(BatchAnnotateImagesResponse response) {
    Log.d(TAG, ":: " + response.getResponses().toString());
    List<FaceAnnotation> faces = response.getResponses().get(0).getFaceAnnotations();
    List<EntityAnnotation> labels = response.getResponses().get(0).getLabelAnnotations();

    // Label string to be populated with data for TextToSpeech
    String label = "";
    if (labels != null && labels.size() > 0) {
        label = "The image may contain ";
        List<Animator> scoreViewAnimations = new ArrayList<>();
        List<Animator> scoreAlphaAnimations = new ArrayList<>();
        List<Animator> showScoreAnimations = new ArrayList<>();

        for (EntityAnnotation l : labels) {
            if (l.getScore() < 0.6f) {
                continue;
            }//from www .  ja  v a 2s.co m

            // Add label description (ex. laptop, desk, person, etc.)
            label += l.getDescription() + ", ";

            /**
             * Create a new {@link ScoreView} and populate it with label description and score
             */
            ScoreView scoreView = new ScoreView(MainActivity.this);
            int padding = (int) DeviceDimensionsHelper.convertDpToPixel(8, this);
            scoreView.setPadding(padding, padding, padding, padding);
            scoreView.setScore(l.getScore());
            scoreView.setLabelPosition(ScoreView.LABEL_POSITION_RIGHT);
            scoreView.setLabelText(l.getDescription());
            scoreView.setAlpha(0f);
            scoreView.setTranslationX((DeviceDimensionsHelper.getDisplayWidth(this) / 2) * -1);

            // Add ScoreView to result layout
            mScoreResultLayout.addView(scoreView);

            // Create animations to used to show the ScoreView in a nice way
            ObjectAnimator animator = ObjectAnimator.ofFloat(scoreView, "translationX",
                    (DeviceDimensionsHelper.getDisplayWidth(this) / 2) * -1, 0f);
            animator.setInterpolator(new OvershootInterpolator());
            scoreViewAnimations.add(animator);

            ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(scoreView, "alpha", 0f, 1f);
            scoreAlphaAnimations.add(alphaAnimator);

            // Get the animation to show the actual score from ScoreView object
            showScoreAnimations.addAll(scoreView.getShowScoreAnimationsList());
        }

        // Set reset button visibility to visible
        mButtonReset.setVisibility(View.VISIBLE);

        // Setup and play the animations
        AnimatorSet translationSet = new AnimatorSet();
        translationSet.playSequentially(scoreViewAnimations);
        translationSet.setDuration(300);

        AnimatorSet alphaSet = new AnimatorSet();
        alphaSet.playSequentially(scoreAlphaAnimations);
        alphaSet.setDuration(300);

        AnimatorSet showScoreSet = new AnimatorSet();
        showScoreSet.playTogether(showScoreAnimations);

        showLoading(false);

        AnimatorSet set = new AnimatorSet();
        set.play(translationSet).with(alphaSet).before(showScoreSet);
        set.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                mButtonReset.animate().alpha(1f).start();
            }
        });
        set.start();
    } else {
        // Set reset button visibility to visible
        mButtonReset.setVisibility(View.VISIBLE);
        mButtonReset.setAlpha(1f);
    }

    // Handle detected faces
    String facesFound = "";
    if (faces != null && faces.size() > 0) {
        FaceGraphicOverlay faceGraphicOverlay = new FaceGraphicOverlay(MainActivity.this);
        faceGraphicOverlay.addFaces(faces);
        faceGraphicOverlay.setTag("faceOverlay");
        mCameraPreviewLayout.addView(faceGraphicOverlay);

        facesFound = FaceFoundHelper.getFacesFoundString(this, faces);
    }

    // Add the detected image data to TTS engine
    mTts.speak(label, TextToSpeech.QUEUE_FLUSH, null);
    mTts.speak(facesFound, TextToSpeech.QUEUE_ADD, null);
}

From source file:kr.wdream.storyshop.AndroidUtilities.java

public static void shakeView(final View view, final float x, final int num) {
    if (num == 6) {
        view.setTranslationX(0);/*from  www . ja va2 s.co m*/
        return;
    }
    AnimatorSet animatorSet = new AnimatorSet();
    animatorSet.playTogether(ObjectAnimator.ofFloat(view, "translationX", AndroidUtilities.dp(x)));
    animatorSet.setDuration(50);
    animatorSet.addListener(new AnimatorListenerAdapterProxy() {
        @Override
        public void onAnimationEnd(Animator animation) {
            shakeView(view, num == 5 ? 0 : -x, num + 1);
        }
    });
    animatorSet.start();
}

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

/**
 * Animates the view based on the custom animator list built with {@link #getAnimators(View, int, boolean)}.
 *//*from   w ww  . j a  v  a2  s . c  om*/
public final void animateView(final View itemView, int position, boolean isSelected) {
    //FIXME: first completed visible item on rotation gets high delay

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

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

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

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

        //Add Alpha animator if not yet
        ViewCompat.setAlpha(itemView, 0);
        if (!animatorsUsed.contains(AnimatorEnum.ALPHA))
            addAlphaAnimator(animators, itemView, 0f);
        //Clear animators since the new item might have different animations
        animatorsUsed.clear();

        //Execute the animations all together
        AnimatorSet set = new AnimatorSet();
        set.playTogether(animators);
        //TODO: Animate with Solution 1 or 2?
        //set.setStartDelay(calculateAnimationDelay1(position));
        set.setStartDelay(calculateAnimationDelay2(position));
        set.setInterpolator(mInterpolator);
        set.setDuration(mDuration);
        set.addListener(new HelperAnimatorListener(itemView.hashCode()));
        set.start();
        if (DEBUG)
            Log.v(TAG, "Started Animation on position " + position + " animatorsUsed=" + animatorsUsed);
        mAnimators.put(itemView.hashCode(), set);
    }

    if (mAnimatorNotifierObserver.isPositionNotified())
        mAnimatorNotifierObserver.clearNotified();

    mLastAnimatedPosition = position;
}

From source file:com.modprobe.profit.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./*from   w w w  .j av  a  2s.  co  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) {
    final SuggestionExpandingListViewItem viewObject = (SuggestionExpandingListViewItem) getItemAtPosition(
            getPositionForView(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 AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT,
            viewObject.getCollapsedHeight()));

    /* 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 AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT,
                            AbsListView.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:com.modprobe.profit.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./*  w ww .  j av  a2  s  . c o  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.
 *
 * 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.
 *
 * 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.
 *
 * 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) {
    final SuggestionExpandingListViewItem viewObject = (SuggestionExpandingListViewItem) getItemAtPosition(
            getPositionForView(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.shoshin.paidpay.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.//from  w  w  w  .ja va2s  .  c  om
 *
 * 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) {
    final ExpandableListItem viewObject = (ExpandableListItem) getItemAtPosition(getPositionForView(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 AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT,
            viewObject.getCollapsedHeight()));

    /* 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. */
            //TODO
            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 AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT,
                            AbsListView.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);
                    invalidateViews();
                }
            });
            s.start();

            return true;
        }
    });
}

From source file:com.shoshin.paidpay.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./*from w  w w.  j a v  a  2  s .  c  o 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.
 *
 * 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.
 *
 * 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.
 *
 * 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) {
    final ExpandableListItem viewObject = (ExpandableListItem) getItemAtPosition(getPositionForView(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. */
            //TODO
            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.ferdi2005.secondgram.AndroidUtilities.java

public static void shakeView(final View view, final float x, final int num) {
    if (num == 6) {
        view.setTranslationX(0);/* ww  w  . j a  v a2 s  . co  m*/
        return;
    }
    AnimatorSet animatorSet = new AnimatorSet();
    animatorSet.playTogether(ObjectAnimator.ofFloat(view, "translationX", AndroidUtilities.dp(x)));
    animatorSet.setDuration(50);
    animatorSet.addListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
            shakeView(view, num == 5 ? 0 : -x, num + 1);
        }
    });
    animatorSet.start();
}

From source file:com.shoshin.paidpay.ExpandingListViewPayVia.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./*from   ww w  .j av a2 s.c  om*/
 *
 * 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) {
    final ExpandableCardsWithOffers viewObject = (ExpandableCardsWithOffers) getItemAtPosition(
            getPositionForView(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 AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT,
            viewObject.getCollapsedHeight()));

    /* 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. */
            //TODO
            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 AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT,
                            AbsListView.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);
                    invalidateViews();
                }
            });
            s.start();

            return true;
        }
    });
}