我在下面发布的所有代码都像我想要的那样工作,只是将其作为参考,也可能是希望实现类似功能的人。它很简单,评论很好。Android动画副作用:按钮在动画颜色时更改其形状
所以有,我正在开发一个应用程序,我有动态创建的几个圆形按钮基于这样定义的XML绘制资源:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<corners
android:radius="25dp"
/>
<solid
android:color="#0000FF"
/>
<padding
android:left="0dp"
android:top="0dp"
android:right="0dp"
android:bottom="0dp"
/>
<size
android:width="50dp"
android:height="50dp"
/>
</shape>
它是用于创建存储阵列中的按钮(gameButtons
)如下所示。 (正如你所看到的,我将随机放置在屏幕上)。它工作正常:
for(int i = 0; i < (numberOfButtons); i++)
{
//create a button:
Button oneBtn = new Button(this);
//get layout reference:
RelativeLayout rl = (RelativeLayout) findViewById(R.id.game_window);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(btnSize, btnSize);
//get screen size:
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
//randomize button's position:
Random r = new Random();
int randX = r.nextInt(height - btnSize);
int randY = r.nextInt(width - btnSize);
params.leftMargin = randY;
params.topMargin = randX;
//set button's parameteres:
oneBtn.setId(i);
oneBtn.setText(String.valueOf(i));
//make the button round, based on drawable/buttonshape.xml:
oneBtn.setBackgroundResource(R.drawable.buttonshape);
//add button to the view:
gameButtons[i] = oneBtn;
rl.addView(oneBtn, params);
}
然后,我想对这些按钮应用动画。动画只是使按钮通过改变其颜色几次(蓝色 - >黄 - >蓝 - > ...) 这个动画工作正常,以及(我想要做什么)
private void changeButtonColor(final Button button){
int animationTime = 800;
//set colors rgb->int
int blueInt = Color.rgb(0,0,255);
int yellowInt = Color.rgb(255,255,0);
//craete an animation:
ValueAnimator anim = new ValueAnimator();
anim.setIntValues(blueInt, yellowInt, blueInt);
anim.setEvaluator(new ArgbEvaluator());
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
//animate button's color:
button.setBackgroundColor((Integer)valueAnimator.getAnimatedValue());
}
});
//final settings to animation an start:
anim.setInterpolator(new LinearInterpolator());
anim.setDuration(animationTime);
anim.start();
}
和按钮闪烁闪烁就像我想要的,但事实上,当我调用changeButtonColor()
我的按钮将它们的形状变成方形。
看起来像上面的动画覆盖什么setBackgroundResource()
不过,我试图通过在动画中放入setBackgroundResource()
而不是结果在很多方面来防止这种情况。
任何建议如何消除这种副作用?