How to prevent Thread.Sleep in onDraw affecting ot

2019-08-27 22:12发布

问题:

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