改变Android的按钮颜色不断
我有我的应用程序一个简单的按钮。
我要做到以下几点事情:
当应用程序运行,按钮的颜色发生变化连续地(例如每3秒)没有任何接触或聚焦,赶上客户的眼睛点击它。
有没有办法做到这一点?改变Android的按钮颜色不断
使用以下代码:
Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run()
{
int rnd = (int)(Math.random() * 4);
if(rnd==0)
btn.setBackgroundColor(Color.BLUE);
if(rnd==1)
btn.setBackgroundColor(Color.RED);
if(rnd==2)
btn.setBackgroundColor(Color.GREEN);
if(rnd==3)
btn.setBackgroundColor(Color.YELLOW);
btn.invalidate();
handler.postDelayed(runnable, 3000);
}
};
handler.postDelayed(runnable, 3000);
什么是invalidate(); ?日食不认识它 –
删除它后尝试。 –
无效()是用于刷新视图 –
对于重复的颜色 -
Button btn = (Button) findViewById(R.id.btn);
Handler handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
int i = 0;
if (i == 0) {
btn.setBackgroundColor(Color.YELLOW);
i++;
} else if (i == 1) {
btn.setBackgroundColor(Color.RED);
i++;
} else if (i == 2) {
btn.setBackgroundColor(Color.BLUE);
i++;
} else if (i == 3) {
btn.setBackgroundColor(Color.GREEN);
i = 0;
}
handler.postDelayed(this, 3000); // Set time in milliseconds
}
};
handler.postDelayed(r, 3000); // Set time in milliseconds
此代码改变按钮的颜色的顺序每隔3秒 - 黄,红,蓝,绿。
随机颜色 -
Button btn = (Button) findViewById(R.id.btn);
Handler handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
int i = (int) Math.random() * 3;
if (i == 0) {
btn.setBackgroundColor(Color.YELLOW);
} else if (i == 1) {
btn.setBackgroundColor(Color.RED);
} else if (i == 2) {
btn.setBackgroundColor(Color.BLUE);
} else if (i == 3) {
btn.setBackgroundColor(Color.GREEN);
}
handler.postDelayed(this, 3000); // Set time in milliseconds
}
};
handler.postDelayed(r, 3000); // Set time in milliseconds
如果你喜欢这个答案,请把它标记为selected
。
感谢,但颜色变为蓝色一次,然后它不更改为其他颜色 –
@PouyaHeydari删除'无效()'请 – FadedCoder
@PouyaHeydari试试我的新代码,我更新了它。 – FadedCoder
在绘制的XML文件中声明的动画
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="true">
<item android:drawable="@drawable/frame1" android:duration="50" />
<item android:drawable="@drawable/frame2" android:duration="50" />
<item android:drawable="@drawable/frame3" android:duration="50" />
etc...
</animation-list>
,然后在代码中你可以写
imageView.setBackgroundResource(R.drawable.movie);
AnimationDrawable anim = (AnimationDrawable)
imageView.getBackground();
anim.start();
哦,是的,但你尝试过什么? –
使用'Handler'或'runOnUi thread' – Rustam