Reputation: 16226
I have been developing an Android app.
I would like to hide the OK button after the user presses it, as the dialog window will stay at the foreground for some seconds while a computation takes place.
This is the code:
new AlertDialog.Builder(this)
.setMessage("This may take a while")
.setPositiveButton("OK", new android.content.DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// hide the OK button - how?
// a lot of computation
}
})
.show();
How can I achieve that?
P.S.: I am not interesting to more advanced techniques to handle a computation (such as: progress dialogs, multi-threading).
Thanks.
Upvotes: 11
Views: 23600
Reputation: 19524
For anyone else trying to disable the Positive button on an AlertDialog
, a lot of these solutions don't seem to work now - you can't grab a reference to the button as soon as you call create
on the AlertDialog.Builder
, it'll just return null.
So one place it should be available is in onResume
, so the way I got this to work was something like this:
var positiveButton: Button? = null
override fun onResume() {
super.onResume()
if (positiveButton == null) {
positiveButton = (dialog as AlertDialog).getButton(AlertDialog.BUTTON_POSITIVE)
}
}
and that way you should have a reference available whenever your fragment is running, so you can just call positiveButton.isEnabled = false
whenever you need to disable it.
Just be careful with your state, a recreated fragment might have some checked boxes or whatever, but it won't have that positiveButton
reference yet, and it'll re-run that code in onResume
. So if you need to do any initialisation (like disabling the button until the user selects an option) make sure you call a function that checks the current state and decides whether the button should be enabled or not. Don't assume it's just starting up blank!
Upvotes: 1
Reputation: 139
setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
where dialog
is DialogInterface
.
Upvotes: 1
Reputation: 4024
You can set the visibility of button to invisible.
ok.setVisibility(View.INVISIBLE);
Upvotes: -3
Reputation: 28418
.setPositiveButton("OK", new android.content.DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
((AlertDialog)dialog).getButton(which).setVisibility(View.INVISIBLE);
// the rest of your stuff
}
})
Upvotes: 22