我在线性布局中有两个 View ,我以编程方式更改了它们的 layout_weight 属性。有没有一种方法可以为这种重量变化设置动画,所以当重量改变时, View 会滑向新的尺寸?
最佳答案
您可以简单地使用 ObjectAnimator。
ObjectAnimator anim = ObjectAnimator.ofFloat(
viewToAnimate,
"weight",
startValue,
endValue);
anim.setDuration(2500);
anim.start();
一个问题是 View 类没有 setWeight() 方法(ObjectAnimator 需要它)。为了解决这个问题,我编写了简单的包装器来帮助归档 View 权重动画。
public class ViewWeightAnimationWrapper {
private View view;
public ViewWeightAnimationWrapper(View view) {
if (view.getLayoutParams() instanceof LinearLayout.LayoutParams) {
this.view = view;
} else {
throw new IllegalArgumentException("The view should have LinearLayout as parent");
}
}
public void setWeight(float weight) {
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
params.weight = weight;
view.getParent().requestLayout();
}
public float getWeight() {
return ((LinearLayout.LayoutParams) view.getLayoutParams()).weight;
}
}
这样使用:
ViewWeightAnimationWrapper animationWrapper = new ViewWeightAnimationWrapper(view);
ObjectAnimator anim = ObjectAnimator.ofFloat(animationWrapper,
"weight",
animationWrapper.getWeight(),
weight);
anim.setDuration(2500);
anim.start();
关于android - 无论如何以编程方式动画线性布局的布局权重属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11506381/