1

我需要让布局背景闪烁或闪烁,每秒都在变化。我写了这段代码:

int colours[]={0xff00ff00, 0xffff0000, 0xff0000ff,0xffffffff};
RelativeLayout fondo;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    fondo = (RelativeLayout) findViewById(R.id.fondo);
    this.fondo.setBackgroundColor(colours[0]);
    this.fondo.setOnTouchListener(this);
}

这是 onTouch 方法:

public boolean onTouch(View v, MotionEvent event) {
    if(event.getAction() == MotionEvent.ACTION_UP) {
        int i=1;
        long delay= 1000;
        long time = System.currentTimeMillis();

        while(true) {
            long time2 = System.currentTimeMillis();
            long time3 = (time2 - time);
            if (time3 > delay) {
                this.fondo.setBackgroundColor(colours[i]);
                Log.d("DEBUG", "EEEEEEEEEEEEEEEEEEEEEEEEEEEEE");
                time = System.currentTimeMillis();
                i++;
                if (i >= colores.length)
                    i=0;
            }
        }
    }
    return true;
}

我的问题是我无法每秒更改背景颜色,但我可以每秒编写 Log.d("DEBUG")。

4

2 回答 2

7

你应该使用AnimationDrawable.

如果您在 UI 线程中使用无限循环,则会导致ANR(Android 无响应)窗口

   public boolean onTouch(View v, MotionEvent event) {

        final int DELAY = 100;

        if(event.getAction() == MotionEvent.ACTION_UP) {


            RelativeLayout fondo = (RelativeLayout) findViewById(R.id.fondo);

            ColorDrawable f = new ColorDrawable(0xff00ff00);
            ColorDrawable f2 = new ColorDrawable(0xffff0000);
            ColorDrawable f3 = new ColorDrawable(0xff0000ff);
            ColorDrawable f4 = new ColorDrawable(0xff0000ff);

            AnimationDrawable a = new AnimationDrawable();
            a.addFrame(f, DELAY);
            a.addFrame(f2, DELAY);
            a.addFrame(f3, DELAY);
            a.addFrame(f4, DELAY);
            a.setOneShot(false);

            fondo.setBackgroundDrawable(a); // This method is deprecated in API 16
            // fondo.setBackground(a); // Use this method if you're using API 16
            a.start();
         }
         return true;
    }
于 2012-10-10T02:00:35.687 回答
0

您需要使用计时器和处理程序。在处理程序中更改背景颜色。这里有一个很好的例子,您可以根据需要对其进行自定义。

于 2012-10-10T01:58:15.793 回答