【问题标题】:Changing android Button Color continuously不断改变android按钮颜色
【发布时间】:2015-12-01 11:57:35
【问题描述】:

我的应用中有一个简单的按钮。
我想做以下事情:
当应用程序运行时,按钮的颜色会不断变化(例如每 3 秒),无需任何触摸或聚焦,以吸引客户点击它。
有什么办法吗?

【问题讨论】:

  • 哦,是的,但是您尝试过什么?
  • 使用HandlerrunOnUi thread

标签: android eclipse button colors


【解决方案1】:

使用下面的代码:

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() 用于刷新视图
  • 颜色变为蓝色一次,不再变为其他颜色
  • 替换 btn.invalidate();代替 invalidate();
【解决方案2】:

用于重复颜色 -

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 请删除invalidate()
【解决方案3】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-24
    • 2021-07-02
    • 2022-01-02
    • 2015-11-23
    • 2015-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多