动画更改android RelativeLayout的宽度

时间:2013-05-20 02:00:55

标签: android animation

我需要以动画方式以编程方式将RelativeLayout的宽度从0更改为600px。我正在使用以下代码:

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);

然而,由于某种原因,这是行不通的。有人能指出我正确的方向吗?

3 个答案:

答案 0 :(得分:45)

我只是输入了这个并且在这里工作得很完美

<强>动画

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;
    }
}

<强>使用

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);
}

答案 1 :(得分:0)

而不是setLayoutParams(),在宽度更改后调用requestLayout()

答案 2 :(得分:0)

这对我有用:

public class CloseImageFromRightToLeft extends Animation {
    private final int newWidth;
    private final int newHeight;
    private final int originalWidth;
    private ImageView mView;

    public CloseImageFromRightToLeft(ImageView v, int[] widthAndHeight) {
        mView = v;
        this.newWidth = widthAndHeight[0] / 3;
        this.originalWidth = widthAndHeight[0];
        this.newHeight = widthAndHeight[1];
    }

    @Override
    public void initialize(int width, int height, int parentWidth, int parentHeight) {
        super.initialize(width, height, parentWidth, parentHeight);
    }

    @Override
    public boolean willChangeBounds() {
        return true;
    }

    @Override
    public void applyTransformation(float interpolatedTime, Transformation t) {
        int newWidth = originalWidth + (int) ((this.newWidth - originalWidth) * interpolatedTime);


        LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(newWidth, this.newHeight);
        mView.setLayoutParams(parms);
        mView.requestLayout();
    }
}