警报框在取消时消失但又回来困扰?

时间:2011-09-02 20:22:47

标签: android multithreading

我想要做的就是显示一个1000毫秒的文本然后得到下一个东西..对话框弹出很慢所以我使用了textview ..但它不能正常工作..给出了代码片段.. 我究竟做错了什么?

Thread sleep_for_sometime = new Thread() {
                public void run() {
                    try {
                        correct.setVisibility(TextView.VISIBLE);
                        sleep(1000);
                        correct.setVisibility(TextView.INVISIBLE);

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    finally {
                        get_question(questionset[i]);
                    }
                }
            };
            //sleep_for_sometime.setDaemon(false);
            sleep_for_sometime.start();

3 个答案:

答案 0 :(得分:3)

您应该更改UI线程中的可见性。阅读painless threading

答案 1 :(得分:2)

AsyncTask很棒,但我认为在某些方面过度使用。只需使用post / postDelayed即可。你不是真正做后台工作,你只是想延迟一些UI线程的工作。绝对阅读Nikita的链接,但我会做类似的事情:

correct.setVisibility(View.VISIBLE);
correct.postDelayed(new Runnable() {
    correct.setVisibility(View.INVISIBLE);
    get_question(questionset[i]);
}, 1000);

答案 2 :(得分:1)

扩展Nikita的答案,你可以做这样的事情

private class SleepTask extends AsyncTask<Void,Integer,Void> {

    @Override
    protected Void doInBackground(Void... params) {
        try {
                publishProgress(0);
                sleep(1000);
                publishProgress(1);
            }catch(Exception e){
                //null
                }
    }

    @Override
    protected void onProgressUpdate(Integer... i){
            if(i[0]==0){
                correct.setVisibility(TextView.VISIBLE);
            }else{
                correct.setVisibility(TextView.INVISIBLE);
            }

    }
    @Override
    protected void onPostExecute(Void res) {
            get_question(questionset[i]);
     }

    @Override
    protected void onPreExecute() {
        //do something before execution
    }
}

启动线程,执行此操作

new SleepTask().execute();