ProgressDialog未显示在活动中

web*_*ius 2 android progressdialog

我想在我的应用程序中包含ProgressDialog.但它没有出现.

这是我使用ProgressDialog的代码片段:

public class abcActivity extends Activity {
    public boolean onOptionsItemSelected(MenuItem item) {
        case XYZ:
            ProgressDialog dialog = ProgressDialog.show(abcActivity.this, "", "Please wait for few seconds...", true);
            callSomeFunction();
            dialog.dismiss();
            showToast(getString(R.string.SomeString));
            break;
    }
}
Run Code Online (Sandbox Code Playgroud)

有谁知道为什么对话框没有出现?有线索吗?

And*_*oid 9

我认为你的代码在某种意义上是错误的,你在UI线程中做了所有事情.你必须将callsomefunction()放入后台线程.

public void runSomething()
{
    showDialog(BACKGROUND_ID);
    Thread t = new Thread(new Runnable() 
    {                   
        public void run() 
        {
            //do something
            handler.post(finishThread);
        }
    });

    t.start();
    // The progress wheel will only show up once all code coming here has been executed
}
Run Code Online (Sandbox Code Playgroud)

还有

protected Dialog onCreateDialog(int id)
{
    if(progressDialog == null) progressDialog = new ProgressDialog(this);
    return progressDialog;
}

@Override
protected void onPrepareDialog(int id, Dialog dialog)
{
    if(id == BACKGROUND_ID) 
    {
        progressDialog.setIndeterminate(true);
        progressDialog.setCancelable(false);
        progressDialog.setMessage("running for long ...");
    }
}

Runnable finishThread = new Runnable()
{       
    public void run() 
    {
//long running
        if(progressDialog != null) progressDialog.dismiss();
    }
};
Run Code Online (Sandbox Code Playgroud)

  • 这不是ProgressDialog.它是任何UI组件.您在UI线程中,因此在使用线程执行其他操作时无法更新其他UI组件.要么产生另一个线程来更新UI,要么产生另一个线程来执行你的工作都是可以接受的解决方案. (3认同)