在 Android 中设置“高度视图”以将父级与动画匹配



单击时如何将视图的高度更改为match_parent?

public class ResizeAnimation extends Animation {
    final int startHeight;
    final int targetHeight;
    private final boolean isOpen;
    View view;
    public ResizeAnimation(View view, int height, boolean isOpen) {
        this.view = view;
        this.targetHeight = height;
        this.isOpen = isOpen;
        startHeight = view.getHeight();
    }
    @Override
     protected void applyTransformation(float interpolatedTime, Transformation t) {
        int newHeight;
        if (isOpen) {
            newHeight = (int) (startHeight + (targetHeight - startHeight) * interpolatedTime);
        } else {
            newHeight =  (int) (startHeight + targetHeight * interpolatedTime);
        }
        view.getLayoutParams().height = newHeight;
        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;
    }
}

ResizeAnimation resizeAnimation = new ResizeAnimation(view, MATCH_PARENT, false);
resizeAnimation.setDuration(500);
view.startAnimation(resizeAnimation);

动画不起作用,因为您传递View.MATCH_PARENT(值为 -1(作为目标高度。引用文档:

国际 MATCH_PARENT [...] 常量值: -1 (0xffffffff(

你必须通过真正的目标高度。您可以在渲染父布局后在父布局中测量未来的目标高度(我建议您为此ViewTreeObserver.onGlobalLayout()(。

最新更新