Reputation: 2013
I need to make a layout background flash or blink, changing every second. I wrote this code:
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);
}
Here is the onTouch method:
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;
}
My problem is that I can't change the background color every second, but I can write the Log.d("DEBUG") every second.
Upvotes: 1
Views: 4270
Reputation:
You should use AnimationDrawable
.
If you use an infinite loop in a UI Thread it causes ANR (Android Not Responding) Window
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;
}
Upvotes: 7