Android: Expand/collapse animation

后端 未结 30 2180
说谎
说谎 2020-11-22 05:01

Let\'s say I have a vertical linearLayout with :

[v1]
[v2]

By default v1 has visibily = GONE. I would like to show v1 with an expand animat

30条回答
  •  旧巷少年郎
    2020-11-22 05:46

    This is a proper working solution, I have tested it:

    Exapnd:

    private void expand(View v) {
        v.setVisibility(View.VISIBLE);
    
        v.measure(View.MeasureSpec.makeMeasureSpec(PARENT_VIEW.getWidth(), View.MeasureSpec.EXACTLY),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
    
        final int targetHeight = v.getMeasuredHeight();
    
        mAnimator = slideAnimator(0, targetHeight);
        mAnimator.setDuration(800);
        mAnimator.start();
    }
    

    Collapse:

    private void collapse(View v) {
        int finalHeight = v.getHeight();
    
        mAnimator = slideAnimator(finalHeight, 0);
    
        mAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animator) {
    
            }
    
            @Override
            public void onAnimationEnd(Animator animator) {
                //Height=0, but it set visibility to GONE
                llDescp.setVisibility(View.GONE);
            }
    
            @Override
            public void onAnimationCancel(Animator animator) {
    
            }
    
            @Override
            public void onAnimationRepeat(Animator animator) {
    
            }
        });
        mAnimator.start();
    }
    

    Value Animator:

    private ValueAnimator slideAnimator(int start, int end) {
        ValueAnimator mAnimator = ValueAnimator.ofInt(start, end);
    
        mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                //Update Height
                int value = (Integer) valueAnimator.getAnimatedValue();
                ViewGroup.LayoutParams layoutParams = llDescp.getLayoutParams();
                layoutParams.height = value;
                v.setLayoutParams(layoutParams);
            }
        });
        return mAnimator;
    }
    

    View v is the view to be animated, PARENT_VIEW is the container view containing the view.

提交回复
热议问题