如何从线程中删除背景



我正在使用计时器定期检查条件,如果发现真实条件,则希望删除背景。但它给了我一个错误。

 android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

我的代码是:

t.schedule(new TimerTask(){
            @Override
            public void run() {
                if(!active){
                    fl.setBackgroundResource(android.R.color.transparent);// this line causing error !
                }

            }}, 500,500);
嗨,

您至少可以使用两种方法来做到这一点:

1. 运行UI读取活动的方法

runOnUiThread(new Runnable(){
     public void run() {
          // UI code goes here
     }
});

2. 处理程序

Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
     public void run() {
          // UI code goes here
     }
});

使用处理程序触摸主线程中的视图,如下所示:

Handler mHandler = new Handler();
t.schedule(new TimerTask(){
mHandler.post(new TimerTask(){
        @Override
        public void run() {
            if(!active){
                fl.setBackgroundResource(android.R.color.transparent);// this line causing error !
            }
        }
        });
        }, 500,500);

最新更新