Reputation: 3767
I have implemented custom dialog in my app with accept and reject buttons. Unless the user clicks either of the buttons within 7 seconds the dismiss method gets fired. I want to dismiss the dialog if the user clicks any time within the 7 seconds but the dismiss method is never fired. I have searched all over SO but I haven't found a solution from the answers.
final Dialog d = new Dialog(MyActivity.this, R.style.Theme_Dialog);
d.setContentView(R.layout.dialog_layout);
d.show();
spRequest.play(spSoundId, 1, 1, 1, 12, 1);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
//dia.dismiss();
d.dismiss();
}
}, 7000); //the alert will play for 7 seconds and stop
Button accept = (Button) d.findViewById(R.id.acpt);
accept.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
d.dismiss();
spRequest.release();
}
});
Button reject = (Button) d.findViewById(R.id.rjct);
reject.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
d.dismiss();
spRequest.release();
msg.setText("");
}
});
Update: after some debugging and research I noticed that if I click on the button twice, the dialog would be dismissed. I am guessing the dialog is drawn twice. I am still working on it. Like @aelimill said, this code works fine when called from the activity body(I tried it in OnCreate()) but the issue comes up when I execute it in a broadcast receiver.
Upvotes: 1
Views: 347
Reputation: 8520
Typically, you override the dialog buttons onClick methods to dismiss them, not buttons outside of the dialog:
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("MyMessage");
alertDialogBuilder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
//do something
}
});
alertDialogBuilder.setNegativeButton("No",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
alertdialog.cancel();
//or alertdialog.dismiss();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
Upvotes: 1