点击后我想逐渐改变按钮颜色。我的意思是,按钮必须具有,例如下一组颜色:默认情况下 - 深蓝色,然后是深蓝色,然后是蓝色,然后是浅蓝色,最后是最亮的蓝色。这只是一个例子,我真的想在循环中更改按钮颜色,就像在下一个代码中一样。但是,我无法理解,为什么它不显示中间色。它仅显示第一种颜色,最后一种颜色显示。
如何改善这个?
public class ActivityExample extends Activity {
private changeColorBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_animations);
changeColorBtn = (Button) findViewById(R.id.btn_change_color);
changeColorBtn.setBackgroundColor(Color.BLACK);
changeColorBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
changeButtonColor(v);
}
});
}
private void changeButtonColor(View v) {
// How many intermediate color will be, and delay in millisecond between them
int count = 20, delay = 100;
for (int i = 0; i < count; i++) {
try {
int color = ((ColorDrawable) changeColorBtn.getBackground())
.getColor();
int blue = Color.blue(color), red = Color.red(color), green = Color.green(color);
changeColorBtn.setBackgroundColor(Color.rgb(red+10, green+5, blue+3));
Thread.sleep(delay);
} catch (InterruptedException inE) {
}
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
答案 0 :(得分:7)
我使用TransitionDrawable解决了这个问题。您可以按照下一步操作:
`
<?xml version="1.0" encoding="UTF-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/color1" />
<item android:drawable="@color/color2" />
</transition>
`
android:background
属性中引用此TransitionDrawable。`
<?xml version="1.0" encoding="UTF-8"?>
<resources>
<color name="color1">#990000</color>
<color name="color2">#cc3311</color>
</resources>
`
并将此xml文件保存在/ res / values /文件夹中,将xml命名为color.xml。
`
int durationMillis = 2000;
TransitionDrawable transition = (TransitionDrawable) changeColorBtn.getBackground();
transition.startTransition(durationMillis);
`
这对我有所帮助,我希望它对其他人有用。