不断改变Android按钮颜色

3

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


哦,是的,但你尝试过什么? - Rohit Gupta
请使用“Handler”或“runOnUiThread线程”。 - Rustam
3个回答

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);

什么是invalidate();?Eclipse无法识别它。 - Pouya Heydari
尝试移除后再试。 - Sagar Zala
invalidate() 用于刷新视图。 - Sagar Zala
颜色会变成蓝色一次,然后就不会再改变为其他颜色了。 - Pouya Heydari
@PouyaHeydari,我找到了解决方案,在Runnable(){...}结束后添加handler.postDelayed(runnable, 3000);。 - Sagar Zala
显示剩余3条评论

0

对于重复的颜色 -

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

如果您喜欢这个答案,请将其标记为已选

感谢,但是一旦颜色变为蓝色,它就不会再改变为其他颜色。 - Pouya Heydari
@PouyaHeydari 请移除 invalidate() - FadedCoder

0
在可绘制的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();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接