在警报对话框中显示进度条。

14

我的应用程序中有一个警告对话框用于登录验证。在发送请求时,我想显示进度条,并且在响应成功后想要关闭它。如果有人知道,请帮帮我。我正在使用以下代码:

final AlertDialog.Builder alert = new AlertDialog.Builder(this);
LinearLayout login = new LinearLayout(this);
TextView tvUserName = new TextView(this);
TextView tvPassword = new TextView(this);
TextView tvURL = new TextView(this);
final EditText etUserName = new EditText(this);
final EditText etPassword = new EditText(this);
final EditText etURL = new EditText(this);
login.setOrientation(1); // 1 is for vertical orientation
tvUserName.setText(getResources().getString(R.string.username));
tvPassword.setText(getResources().getString(R.string.password));
tvURL.setText("SiteURL");
login.addView(tvURL);
login.addView(etURL);
login.addView(tvUserName);
login.addView(etUserName);
login.addView(tvPassword);
etPassword.setInputType(InputType.TYPE_CLASS_TEXT
| InputType.TYPE_TEXT_VARIATION_PASSWORD);
login.addView(etPassword);
alert.setView(login);
alert.setTitle(getResources().getString(R.string.login));
alert.setCancelable(true);
alert.setPositiveButton(getResources().getString(R.string.login),
new DialogInterface.OnClickListener() {
    public void onClick(final DialogInterface dialog,
    int whichButton) {
        strhwdXml = etURL.getText().toString();
        strUserName = etUserName.getText().toString();
        XmlUtil.username = strUserName;
        strPassword = etPassword.getText().toString();
        if ((strUserName.length() == 0)
        && (strPassword.length() == 0)
        && (strhwdXml.length() == 0)) {
            Toast.makeText(
            getBaseContext(),
            getResources().getString(
            R.string.userPassword),
            Toast.LENGTH_SHORT).show();
            onStart();
            } else {
            final SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(getApplicationContext());
            SharedPreferences.Editor prefsEditor = prefs
            .edit();
            try {
                StringBuffer inStreamBuf = new StringBuffer();
                inStreamBuf = XmlUtil
                .getLoginAuthResponse(strUserName,
                strPassword, strhwdXml);
                strXmlResponse = inStreamBuf.toString();
                Log.e("Response:", strXmlResponse);
                String parsedXML = ParseResponse(strXmlResponse);
                if (parsedXML
                .equalsIgnoreCase(getResources()
                .getString(R.string.success))) {
                }

使用异步任务来完成此操作,http://droidapp.co.uk/?p=177 - Aerrow
如果您在XML中定义布局,可能会更容易。 - jiduvah
我该怎么做才能完成这个...请帮帮我 jiduvah - user1004789
http://developer.android.com/guide/topics/ui/declaring-layout.html - jiduvah
4个回答

32

也许使用这个会更容易

ProgressDialog dialog = ProgressDialog.show(MyActivity.this, "", 
                        "Loading. Please wait...", true);

你可以在这里阅读有关进度对话框的更多信息

取消将是:

    dialog.dismiss();

这个类在API水平26中已被弃用。ProgressDialog是一种模态对话框,会阻止用户与应用程序交互。不建议使用此类,您应该使用进度指示器(如ProgressBar),它可以嵌入您的应用程序界面。或者,您可以使用通知来通知用户任务的进度。了解更多信息请 点击此处


如果认证响应成功,如何取消它?!? - user1004789
那会打开一个新的对话框,是吗?这是期望的效果吗?您还可以将ProgressDialog添加到对话框本身中。 - MikeIsrael
它将打开一个新的对话框,是的。 - jiduvah
进度条已打开,但如果响应成功,它不会继续前进。 - user1004789
9
ProgressDialog已被弃用,并且不能与appcompat库一起使用。 - Brill Pappin

11

由于 ProgressDialog 类已被弃用,这里提供一种在 AlertDialog 中显示 ProgressBar 的简单方法:

  1. 在你的 Activity 中添加字段:

  2. AlertDialog.Builder builder;
    AlertDialog progressDialog;
    
  3. 在您的Activity中添加getDialogProgressBar()方法:

  4. public AlertDialog.Builder getDialogProgressBar() {
    
      if (builder == null) {
        builder = new AlertDialog.Builder(this);
    
        builder.setTitle("Loading...");
    
        final ProgressBar progressBar = new ProgressBar(this);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);
        progressBar.setLayoutParams(lp);
        builder.setView(progressBar);
      }
      return builder;
    }
    
  5. 初始化progressDialog

    progressDialog = getDialogProgressBar().create();
    
  6. 使用实用方法随时显示/隐藏AlertDialog:

    progressDialog.show()progressDialog.dismiss()


1
当应用程序第二次重新启动时,调用show()方法时,我会收到一个“非法状态异常:指定的子项已经有一个父项。您必须首先在子项的父项上调用removeView()。”的错误提示。 - SMBiggs
1
@ScottBiggs 你好,你解决了那个问题还是仍然面临着同样的问题? - Sandeep Yohans
是的!不寻常的是,当您重新启动应用程序时,对话框似乎仍然可以在内存中。因此,请确保在上下文被销毁时调用builder = null。我在这个对话框类中添加了一个destroyDialog()方法,并在Activity的onDestroy()方法中调用它。如果这不清楚,让我知道,我会将其作为另一个答案添加。 - SMBiggs
“lp”的作用是什么?无论是否使用它,对话框都会根据“ProgressBar”的高度进行调整,但宽度始终保持不变。 - Neph

4
如果您想显示进度条,请尝试以下步骤,您还可以复制并粘贴整个代码的相关部分,它应该可以工作。
//the first thing you need to to is to initialize the progressDialog Class like this

final ProgressDialog progressBarDialog= new ProgressDialog(this);

//set the icon, title and progress style..

progressBarDialog.setIcon(R.drawable.ic_launcher);

progressBarDialog.setTitle("Showing progress...");

progressBarDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);


    //setting the OK Button
    progressBarDialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener(){
        public void onClick(DialogInterface dialog,
                int whichButton){
            Toast.makeText(getBaseContext(),
                    "OK clicked!", Toast.LENGTH_SHORT).show();
        }
    });

    //set the Cancel button
    progressBarDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener(){
        public void onClick(DialogInterface dialog, int whichButton){
            Toast.makeText(getApplicationContext(), "Cancel clicked", Toast.LENGTH_SHORT).show();
        }
    });
//initialize the dialog..
progressBarDialog.setProgress(0);

//setup a thread for long running processes
new Thread(new Runnable(){
    public void run(){
        for (int i=0; i<=15; i++){
            try{
                Thread.sleep(1000);
                progressBarDialog.incrementProgressBy((int)(5));
            }
            catch(InterruptedException e){
                e.printStackTrace();
            }
        }
        //dismiss the dialog
        progressBarDialog.dismiss();
     }
   });

//show the dialog
progressBarDialog.show();

取消按钮应该关闭对话框。

1
请注意,ProgressDialog现已被弃用,因此不应使用它。 - natansalda

0

尝试下面的代码

  private class DownloadingProgressTask extends
        AsyncTask<String, Void, Boolean> {

    private ProgressDialog dialog = new ProgressDialog(ShowDescription.this);

    /** progress dialog to show user that the backup is processing. */

    /** application context. */

    protected void onPreExecute() {
         this.dialog.setMessage("Please wait");
         this.dialog.show();
    }

    protected Boolean doInBackground(final String... args) {
        try {
            // write your request code here


            **StringBuffer inStreamBuf = new StringBuffer();
            inStreamBuf = XmlUtil
            .getLoginAuthResponse(strUserName,
            strPassword, strhwdXml);
            strXmlResponse = inStreamBuf.toString();
            Log.e("Response:", strXmlResponse);
            String parsedXML = ParseResponse(strXmlResponse);
            if (parsedXML
            .equalsIgnoreCase(getResources()
            .getString(R.string.success))) {**

              return true;
        } catch (Exception e) {
            Log.e("tag", "error", e);
            return false;
        }
    }

    @Override
    protected void onPostExecute(final Boolean success) {

        if (dialog.isShowing()) {
            dialog.dismiss();
        }

        if (success) {
            Toast.makeText(ShowDescription.this,
                    "File successfully downloaded", Toast.LENGTH_LONG)
                    .show();
            imgDownload.setVisibility(8);
        } else {
            Toast.makeText(ShowDescription.this, "Error", Toast.LENGTH_LONG)
                    .show();
        }
    }

}

并在onclick事件中调用此函数

new DownloadingProgressTask().execute();

你能帮我修改代码并告诉我如何在我的应用程序中实现吗? - user1004789

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接