【发布时间】:2015-12-01 11:57:35
【问题描述】:
我的应用中有一个简单的按钮。
我想做以下事情:
当应用程序运行时,按钮的颜色会不断变化(例如每 3 秒),无需任何触摸或聚焦,以吸引客户点击它。
有什么办法吗?
【问题讨论】:
-
哦,是的,但是您尝试过什么?
-
使用
Handler或runOnUi thread
标签: android eclipse button colors
我的应用中有一个简单的按钮。
我想做以下事情:
当应用程序运行时,按钮的颜色会不断变化(例如每 3 秒),无需任何触摸或聚焦,以吸引客户点击它。
有什么办法吗?
【问题讨论】:
Handler 或runOnUi thread
标签: android eclipse button colors
使用下面的代码:
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);
【讨论】:
用于重复颜色 -
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。
【讨论】:
invalidate()
在可绘制的 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();
【讨论】: