onBackPressed() doesn't trigger when showing ProgressDialog

只愿长相守 提交于 2019-12-11 13:56:43

问题


I have tried a lot of ways to trigger the backPressed() event when the progressDialog is displayed. But none works. If I provide progDialog.setcancelable(true); I am able to dismiss the progressDialog but still the onBackPressed() doesn't get triggered.


回答1:


When ProgressDialog is active if yiou press back key to perform yopur own operations you have to set setOnCancelListener to the progressdialog. write your logic inside onCancel() method example the whole logic that you have written in onBackPressed() event those things you have to write here.

Sample code

import android.app.Activity;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;

import android.os.Bundle;

import android.view.KeyEvent;
import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

public class CancelProgressDialog extends Activity {

    ProgressDialog myProgressDialog = null;

    @Override
    public void onCreate(Bundle icicle) {

        super.onCreate(icicle);

        /* Create a very simple button */

        Button b = new Button(this);

        this.setContentView(b);

        b.setText("Show ProgressBar...");

        b.setOnClickListener(myProgressBarShower);

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        System.out.println("...any key is pressed....");
        if (keyCode == KeyEvent.KEYCODE_BACK)
        {
            System.out.println("...BackButton is pressed...");
            if( (myProgressDialog!= null) && myProgressDialog.isShowing()){
                myProgressDialog.dismiss();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    /** OnClickListener that fakes some work to be done. */

    OnClickListener myProgressBarShower = new OnClickListener() {

        // @Override

        public void onClick(View arg0) {

            // Display an indeterminate Progress-Dialog

            myProgressDialog = ProgressDialog.show(CancelProgressDialog.this,

            "Please wait...", "Doing Extreme Calculations...", true);
            myProgressDialog.setOnCancelListener(new OnCancelListener() {

                public void onCancel(DialogInterface arg0) {
                    // TODO Auto-generated method stub
                    System.out.println("...cancel button is pressed");
//                  perform your task here
                }
            });
            myProgressDialog.setCancelable(true);



        }



    };

}

Thanks Deepak



来源:https://stackoverflow.com/questions/6356956/onbackpressed-doesnt-trigger-when-showing-progressdialog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!