How to remove background from thread

瘦欲@ 提交于 2019-12-11 17:45:28

问题


I am using Timer to check a condition periodically and want to remove background if found true condition. But it is giving me an error.

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

My code is :

t.schedule(new TimerTask(){

            @Override
            public void run() {

                if(!active){
                    fl.setBackgroundResource(android.R.color.transparent);// this line causing error !

                }


            }}, 500,500);

回答1:


Hi you can use at least two methods to do that:

1. runOnUIThread Activity's method

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

2. Handler

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



回答2:


Use handler to touch views in main thread like that:

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);


来源:https://stackoverflow.com/questions/22847440/how-to-remove-background-from-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!