如何设置布局的宽度和高度的动画?

P R*_*ant 6 java android android-animation android-layout

我有一个LinearLayout通过隐藏所有其他布局和视图扩展到全屏幕onClick.有一个Relativelayout上面LinearLayout

我想对此应用自定义动画.尺寸应该缓慢增加(如在500毫秒内).

但我怀疑是否可能?谢谢.

这是我在做的事情onClick:

private void expandView (int viewId) {
    RelativeLayout relativeLayout = (RelativeLayout) ((LinearLayout) view.findViewById(viewId)).getParent();
    ViewGroup.MarginLayoutParams rlMargin = (ViewGroup.MarginLayoutParams) relativeLayout.getLayoutParams();
    rlMargin.setMargins(0, 0, 0, 0);
    relativeLayout.setLayoutParams(rlMargin);
    LinearLayout linearLayout = (LinearLayout) relativeLayout.getParent();
    hideAllLinearLayoutExcept(linearLayout.getId());
    hideAllTilesExcept(viewId);
}
Run Code Online (Sandbox Code Playgroud)

viewIdLinearLayout我点击的ID .从中调用此函数onClick()

Phi*_*oda 16

当然有可能.

只需编写自己的自定义动画并修改LayoutParams动画视图.在此示例中,动画为动画视图的高度设置动画.当然,也可以设置宽度的动画.

这是它的样子:

public class ResizeAnimation extends Animation {

    private int startHeight;
    private int deltaHeight; // distance between start and end height
    private View view;

    /**
     * constructor, do not forget to use the setParams(int, int) method before
     * starting the animation
     * @param v
     */
    public ResizeAnimation (View v) {
        this.view = v;
    }

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {

        view.getLayoutParams().height = (int) (startHeight + deltaHeight * interpolatedTime);
        view.requestLayout();
    }

    /**
     * set the starting and ending height for the resize animation
     * starting height is usually the views current height, the end height is the height
     * we want to reach after the animation is completed
     * @param start height in pixels
     * @param end height in pixels
     */
    public void setParams(int start, int end) {

        this.startHeight = start;
        deltaHeight = end - startHeight;
    }

    /**
     * set the duration for the hideshowanimation
     */
    @Override
    public void setDuration(long durationMillis) {
        super.setDuration(durationMillis);
    }

    @Override
    public boolean willChangeBounds() {
        return true;
    }
}   
Run Code Online (Sandbox Code Playgroud)

在代码中,创建一个新动画并将其应用于要设置动画的RelativeLayout:

RelativeLayout relativeLayout = (RelativeLayout) ((LinearLayout) view.findViewById(viewId)).getParent();

// getting the layoutparams might differ in your application, it depends on the parent layout
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) relativeLayout.getLayoutParams();

ResizeAnimation a = new ResizeAnimation(relativeLayout);
a.setDuration(500);

// set the starting height (the current height) and the new height that the view should have after the animation
a.setParams(lp.height, newHeight);

relativeLayout.startAnimation(a);
Run Code Online (Sandbox Code Playgroud)