如何以动画方式编程更改高度布局?
第一步:
之后:
第一步:
![enter image description here](https://istack.dev59.com/8aPF6.webp)
![enter image description here](https://istack.dev59.com/SKGhq.webp)
嘿,Amigo,
在测试我的代码后,我发现了一个小问题。由于我使用了"scaleY"
,它只会将视图"拉伸"。这意味着如果视图中有一些文本或其他东西,它只会将其拉伸,看起来不太好。请尝试使用ValueAnimator
代替,它的效果更加平滑。
public void onClick(View v)
{
if(!isBig){
ValueAnimator va = ValueAnimator.ofInt(100, 200);
va.setDuration(400);
va.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
public void onAnimationUpdate(ValueAnimator animation) {
Integer value = (Integer) animation.getAnimatedValue();
v.getLayoutParams().height = value.intValue();
v.requestLayout();
}
});
va.start();
isBig = true;
}
else{
ValueAnimator va = ValueAnimator.ofInt(200, 100);
va.setDuration(400);
va.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
public void onAnimationUpdate(ValueAnimator animation) {
Integer value = (Integer) animation.getAnimatedValue();
v.getLayoutParams().height = value.intValue();
v.requestLayout();
}
});
va.start();
isBig = false;
}
}
XML:
<RelativeLayout
android:layout_width="150dp"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:background="@android:color/holo_red_dark"
android:onClick="onButtonClick"
android:clickable="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="My Layout"/>
</RelativeLayout>
旧回答
你可以使用ObjectAnimator,只需记得设置,这样它只会在底部移动。自己玩一下,以满足您的需求 :)
新回答
您可以使用 ObjectAnimator,只需记得设置 pivotY(0)
,这样它就只会在底部移动。根据您的需要进行调整即可 :)private boolean isBig = false;
...
public void onClick(View v)
{
v.setPivotY(0f);
if(!isBig){
ObjectAnimator scaleY = ObjectAnimator.ofFloat(v, "scaleY", 2f);
scaleY.setInterpolator(new DecelerateInterpolator());
scaleY.start();
isBig = true;
}
else{
ObjectAnimator scaleY = ObjectAnimator.ofFloat(v, "scaleY", 1f);
scaleY.setInterpolator(new DecelerateInterpolator());
scaleY.start();
isBig = false;
}
}
ValueAnimator
替代,如果视图/布局中有一些文本或其他内容,它将工作得更好。 - Ibrahim Yildirim