我需要让布局背景闪烁或闪烁,每秒都会改变。我写了这段代码:
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”)。
答案 0 :(得分: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;
}
答案 1 :(得分:0)
您需要使用计时器和处理程序。在处理程序中更改背景颜色。 有一个很好的例子here,您可以根据需要自定义它。