android 相对布局的动画更改宽度 [英] Animate change width of android RelativeLayout

查看:31
本文介绍了android 相对布局的动画更改宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

我刚刚输入了这个,在这里工作得很好

I just typed this up and works perfect here

动画

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

更新:Kotlin 版本

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

这篇关于android 相对布局的动画更改宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆