Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Alert Dialog - how to hide the OK button after it being pressed

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.

like image 988
Dan Avatar asked Nov 27 '10 12:11

Dan


2 Answers

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!

like image 128
cactustictacs Avatar answered Oct 30 '22 11:10

cactustictacs


.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
    }
})
like image 40
Vit Khudenko Avatar answered Oct 30 '22 11:10

Vit Khudenko