在ProgressDialog上设置文本会导致应用崩溃

时间:2016-12-23 19:26:31

标签: android

我正在学习android,我不知道为什么这段代码不起作用。你能告诉我为什么它不起作用并带我正确的代码吗?

    final ProgressDialog dialog = ProgressDialog.show(LoginScreen.this, "", "Loading. Please wait...", true);
    Thread loggingStatus = new Thread() {
        public void run() {
            try
            {
                sleep(2000);
                dialog.setMessage("Logging in. Please wait.");
                sleep(2000);
                dialog.dismiss();
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
    };
    loggingStatus.start();

2 个答案:

答案 0 :(得分:0)

您必须将更新ui的后台任务部分移动到主线程上。有一段简单的代码:

  

putting runOnUiThread( new Runnable(){ .. inside run():

  final ProgressDialog dialog = ProgressDialog.show(this, "", "Loading. Please wait...", true);
        Thread loggingStatus = new Thread() {
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            sleep(2000);
                            dialog.setMessage("Logging in. Please wait.");
                            sleep(2000);
                            dialog.dismiss();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    }
                });

            }
        };
        loggingStatus.start();

答案 1 :(得分:-1)

您不应在后台线程中设置Text of ProgressDialog。所有UI更新应仅在UI线程(主线程)

上完成

使用AsyncTaskHandler来表示此逻辑或功能