How to prevent Thread.Sleep in onDraw affecting other Activities?

徘徊边缘 提交于 2019-12-13 03:27:18

问题


I have a custom View class which is drawing images. The problem is that when I use Thread.sleep(200); in the onDraw method, it also affects the XML elements that are in the same activity. So I have to wait 200 miliseconds untill something happens.

MainPage extends Activity implements OnClickListener{
    onCreate(...){

        RelativeLayout rl = (RelativeLayout) findViewById(R.id.main_rl);
        rl.addView(new CustomView(this));
    }

    onClick(View v){
        switch(v.getId){
            ...
        };
    }
}


CustomView extends View{

    onDraw(){
        try{
            Thread.sleep(200);
            ....
        }
    }
}

Any help will be appreciated.


回答1:


Never run long operations in any UI listener callback (or anywhere else that runs on the UI thread) in Android. Instead, create a new thread to perform the sleep and then do whatever needs to be done. Just remember that if you want to interact with the UI again, you need to do that within the UI thread, which you can schedule by calling runOnUiThread().

CustomView extends View{

    onDraw(){
        (new Thread(myRunnable)).start();
    }
}

Runnable myRunnable = new Runnable() {
    void run() {
        try { Thread.sleep(...); } catch...;
        do_non_ui_things_if_needed();
        runOnUiThread(some_runnable_for_this_if_needed);
    }
}


来源:https://stackoverflow.com/questions/14728807/how-to-prevent-thread-sleep-in-ondraw-affecting-other-activities

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