想在onCreate of Activity中显示AlertDialog - android

时间:2011-04-22 13:37:51

标签: android alertdialog showdialog oncreate

在我的活动中,我在onCreate()中调用MyDialog(自定义对话框)并在Activity中处理它的DismissListener以查找是否取消了它。如果取消,我完成活动,否则加载活动。在此加载期间,我想显示一个警报/进度对话框,让用户知道它的加载,请稍候。但我无法看到对话框。这就是我编码的方式:

  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ld = new AgreeDialog(this);
    ld.setOnDismissListener(new OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
           if (ld.isCancelled)
    MyActivity.this.finish();
       else {
    //ProgressDialog pd = CreateLoadingDialog();
    //pd.show();
    //Log.i(TAG, "Before Load Is PD showing - " + pd.isShowing());  // Shows true
          /*
    AlertDialog.Builder adb = new AlertDialog.Builder(StartUltimate.this);
    adb.setTitle("Loading...");
    adb.setCancelable(false);
    AlertDialog ad = adb.create();
    ad.show();
    */  
    MyActivity.this.showDialog(0);
    LoadAfteAgree();  // This takes time sonetimes, so want a dialog while this is working 
    MyActivity.this.removeDialog(0);

    //ad.dismiss();
                // pd.dismiss();
    //Log.i(TAG, "After Load Is PD showing - " + ad.isShowing());    // Shows false
     }
}           
    });

@Override
protected Dialog onCreateDialog(int id) {
    switch(id) {
    case 0:
        loadingDlg = new ProgressDialog(this);
        loadingDlg.setMessage("Loading...");
        loadingDlg.setCancelable(false);
        loadingDlg.setIcon(R.drawable.icon);
        return loadingDlg;
    }
    return null;
}

为什么我无法以任何方式看到任何对话框?我也尝试在LoadAfterAgree()中调用它们,但也没有成功,结果相同。

非常感谢任何帮助。

由于

2 个答案:

答案 0 :(得分:4)

您正在UI线程中执行长时间的操作。将它们移动到AsyncTask的doInBackground方法。请参阅示例here

答案 1 :(得分:3)

要停止对话框导致任何内存泄漏,请确保您的活动中包含以下内容;

AlertDialog _alert;

  @Override
  public void onPause() {
      super.onPause();

      if(_alert != null)
          _alert.dismiss();
  }