如何美元的onDraw p $ pvent了Thread.Sleep影响其他的活动? [英] How to prevent Thread.Sleep in onDraw affecting other Activities?

查看:163
本文介绍了如何美元的onDraw p $ pvent了Thread.Sleep影响其他的活动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个正在起草的图像的自定义视图类。的问题是,当我使用了Thread.sleep(200);在的onDraw方法,它也影响是在相同的活性的XML元素。所以,我要等待200毫秒,直到事情发生。

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

任何帮助将AP preciated。

Any help will be appreciated.

推荐答案

从不运行任何UI侦听器回调长时间操作(或其他地方的UI线程上运行)的Andr​​oid系统。相反,创建一个新的线程来执行睡眠,然后做任何需要做的事情。只要记住,如果你想再次与UI交互,你需要做的UI线程,它可以通过调用计划中的 runOnUiThread()

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

这篇关于如何美元的onDraw p $ pvent了Thread.Sleep影响其他的活动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆