我在我的应用程序中有一个简单的按钮。
我想要做到以下的事情:
当应用程序运行时,按钮的颜色不断地改变(例如每3秒一次),而不需要任何触摸或聚焦,以吸引客户点击它。
有没有什么方法可以做到这一点?
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
已选
。invalidate()
。 - FadedCoder <?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();