Android: Expand/collapse animation

后端 未结 30 2664
说谎
说谎 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:44

    This is a snippet that I used to resize the width of a view (LinearLayout) with animation.

    The code is supposed to do expand or shrink according the target size. If you want a fill_parent width, you will have to pass the parent .getMeasuredWidth as target width while setting the flag to true.

    Hope it helps some of you.

    public class WidthResizeAnimation extends Animation {
    int targetWidth;
    int originaltWidth;
    View view;
    boolean expand;
    int newWidth = 0;
    boolean fillParent;
    
    public WidthResizeAnimation(View view, int targetWidth, boolean fillParent) {
        this.view = view;
        this.originaltWidth = this.view.getMeasuredWidth();
        this.targetWidth = targetWidth;
        newWidth = originaltWidth;
        if (originaltWidth > targetWidth) {
            expand = false;
        } else {
            expand = true;
        }
        this.fillParent = fillParent;
    }
    
    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        if (expand && newWidth < targetWidth) {
            newWidth = (int) (newWidth + (targetWidth - newWidth) * interpolatedTime);
        }
    
        if (!expand && newWidth > targetWidth) {
            newWidth = (int) (newWidth - (newWidth - targetWidth) * interpolatedTime);
        }
        if (fillParent && interpolatedTime == 1.0) {
            view.getLayoutParams().width = -1;
    
        } else {
            view.getLayoutParams().width = newWidth;
        }
        view.requestLayout();
    }
    
    @Override
    public void initialize(int width, int height, int parentWidth, int parentHeight) {
        super.initialize(width, height, parentWidth, parentHeight);
    }
    
    @Override
    public boolean willChangeBounds() {
        return true;
    }
    

    }

提交回复
热议问题