Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
759 views
in Technique[技术] by (71.8m points)

animation - Animate change width of android RelativeLayout

I need to change the width of a RelativeLayout from 0 to 600px programmatically, in an animated way. I'm using the following code:

Animation a = new Animation() {
    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        RelativeLayout.LayoutParams drawerParams = (LayoutParams) drawer.getLayoutParams();
        drawerParams.width = 600;
        drawer.setLayoutParams(drawerParams);
    }
};

a.setDuration(1000); //Animate for 1s
layout.startAnimation(a);

However, for some reason this isn't working. Can anyone point me in the right direction?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I just typed this up and works perfect here

Animation

public class ResizeWidthAnimation extends Animation {
    private int mWidth;
    private int mStartWidth;
    private View mView;
    
    public ResizeWidthAnimation(View view, int width) {
        mView = view;
        mWidth = width;
        mStartWidth = view.getWidth();
    }
    
    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        int newWidth = mStartWidth + (int) ((mWidth - mStartWidth) * interpolatedTime);

        mView.getLayoutParams().width = newWidth;
        mView.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;
    }
}

usage

if (animate) {
    ResizeWidthAnimation anim = new ResizeWidthAnimation(leftFrame, leftFragmentWidthPx);
    anim.setDuration(500);
    leftFrame.startAnimation(anim);
} else {
    this.leftFragmentWidthPx = leftFragmentWidthPx;
    LayoutParams lp = (LayoutParams) leftFrame.getLayoutParams();
    lp.width = leftFragmentWidthPx;
    leftFrame.setLayoutParams(lp);
}

UPDATE: Kotlin Version

class ResizeWidthAnimation(private val mView: View, private val mWidth: Int) : Animation() {
    private val mStartWidth: Int = mView.width

    override fun applyTransformation(interpolatedTime: Float, t: Transformation) {
        mView.layoutParams.width = mStartWidth + ((mWidth - mStartWidth) * interpolatedTime).toInt()
        mView.requestLayout()
    }

    override fun willChangeBounds(): Boolean {
        return true
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...