Android showing progress bar in alert dialog

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10977150/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 05:37:34  来源:igfitidea点击:

showing progress bar in alert dialog

android

提问by jiduvah

I have an alert dialog box in my application for login authentication. While sending the request i want to show a progress bar and want to dismiss if the response is success.please help me if anyone knows.Iam using the below code:

I have an alert dialog box in my application for login authentication. While sending the request i want to show a progress bar and want to dismiss if the response is success.please help me if anyone knows.Iam using the below code:

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))) {
                }

回答by jiduvah

It might be easier to use this

It might be easier to use this

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

You can read more about progress dialogs here

You can read more about progress dialogs here

To cancel would be

To cancel would be

    dialog.dismiss();

This class was deprecated in API level 26. ProgressDialog is a modal dialog, which prevents the user from interacting with the app. Instead of using this class, you should use a progress indicator like ProgressBar, which can be embedded in your app's UI. Alternatively, you can use a notification to inform the user of the task's progress.For more details Click Here

This class was deprecated in API level 26. ProgressDialog is a modal dialog, which prevents the user from interacting with the app. Instead of using this class, you should use a progress indicator like ProgressBar, which can be embedded in your app's UI. Alternatively, you can use a notification to inform the user of the task's progress.For more details Click Here

回答by Alex Irabor

If you want the progress bar to show, try the following steps and also you can copy and paste the entire code the relevant portion of your code and it should work.

If you want the progress bar to show, try the following steps and also you can copy and paste the entire code the relevant portion of your code and it should work.

//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();

The cancel button should dismiss the dialog.

The cancel button should dismiss the dialog.

回答by Sandeep Yohans

Since the ProgressDialogclass is deprecated, here is a simple way to display ProgressBarin AlertDialog:

Since the ProgressDialogclass is deprecated, here is a simple way to display ProgressBarin AlertDialog:

  1. Add fields in your Activity:

    AlertDialog.Builder builder;
    AlertDialog progressDialog;
    
  2. Add getDialogProgressBar() method in your Activity:

    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;
    }
    
  3. Initialize progressDialog:

    progressDialog = getDialogProgressBar().create();
    
  4. Show/Hide AlertDialog whenever u want using utility methods:

    progressDialog.show()and progressDialog.dismiss()

  1. Add fields in your Activity:

    AlertDialog.Builder builder;
    AlertDialog progressDialog;
    
  2. Add getDialogProgressBar() method in your Activity:

    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;
    }
    
  3. Initialize progressDialog:

    progressDialog = getDialogProgressBar().create();
    
  4. Show/Hide AlertDialog whenever u want using utility methods:

    progressDialog.show()and progressDialog.dismiss()

回答by Nirali

Try below code

Try below code

  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();
        }
    }

}

and call this in onclick event

and call this in onclick event

new DownloadingProgressTask().execute();