onBackPressed() doesn't trigger when showing ProgressDialog
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.
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
精彩评论