1 回答

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超4個(gè)贊
編輯
忘記我在原來的帖子中寫的內(nèi)容了。請(qǐng)嘗試下面的代碼,讓我知道這是否對(duì)您有幫助。
final ValueAnimator valueAnimator = ValueAnimator.ofFloat(1.0f, 0.0f); //start and end value
valueAnimator.setDuration(2000); //you can replace 2000 with a variable you can change dynamically
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float animatedValue = (float) animation.getAnimatedValue();
button.setScaleX(animatedValue);
button.setScaleY(animatedValue);
}
});
valueAnimator.start();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
valueAnimator.pause();
}
});
原答案
我會(huì)遵循 0X0nosugar 的建議。
在 Android 文件樹中的 res 目錄下,添加 Android 資源目錄(右鍵單擊 res 文件夾 > 新建)并將其命名為“anim”。如果您使用該名稱,Android Studio 可能會(huì)自動(dòng)將其視為保存動(dòng)畫的文件夾。再次右鍵單擊動(dòng)畫文件夾 > 新建 > 動(dòng)畫資源文件。將其命名為您想要的名稱。在我的示例中,我將其命名為“button_animator”。
您的文件樹將如下所示:
您的button_animator.xml 可能如下所示:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<scale
android:interpolator="@android:anim/accelerate_decelerate_interpolator"
android:fromXScale="1.0"
android:toXScale="0.1"
android:fromYScale="1.0"
android:toYScale="0.1"
android:pivotX="50%"
android:pivotY="50%"
android:fillAfter="false"
android:duration="500" />
</set>
您可以使用以下幾行定制按鈕的最終比例:
android:toXScale="0.1"
和
android:toYScale="0.1"
在代碼中,您可以動(dòng)態(tài)定制動(dòng)畫:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Animation shrinkButton = AnimationUtils.loadAnimation(MainActivity.this, R.anim.button_animator); //reference the animator
shrinkButton.setDuration(5000); //dynamically set the duration of your animation
button.startAnimation(shrinkButton); //start the animation. Since it is inside an onclicklistener, the animation start on a button click event
shrinkButton.setAnimationListener(new Animation.AnimationListener() { //you could use an AnimationListener to do something on certain event, like at the end of the animation
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) { //you probably want to something onAnimationEnd, otherwise the button will snap back into its original size.
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
}
});
在 onAnimationEnd 中,您必須決定在動(dòng)畫結(jié)束時(shí)要執(zhí)行的操作。只是幾個(gè)想法:
@Override
public void onAnimationEnd(Animation animation) { //you probably want to something onAnimationEnd, otherwise the button will snap back into its original size.
button.setScaleX(0.1f); //same size as in toScale size in the animator xml
button.setScaleY(0.1f);
}
或者,如果您希望按鈕變得不可見:
@Override
public void onAnimationEnd(Animation animation) {
button.setVisibility(View.INVISIBLE);
}