本文介绍了我如何做一个布局的背景闪烁的Android?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要做一个布局的背景闪光或闪烁,改变每一秒。我写这篇code:
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);
}
下面是onTouch方式:
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;
}
我的问题是我无法改变的背景颜色每一秒,但我可以写Log.d(调试),每一秒。
My problem is that I can't change the background color every second, but I can write the Log.d("DEBUG") every second.
推荐答案
您应该使用 AnimationDrawable
。
如果您使用的UI无限循环线程会引起 ANR(安卓无响应)窗口
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;
}
这篇关于我如何做一个布局的背景闪烁的Android?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!