User44 User44 - 1 month ago 12
Android Question

Button in AlertDialog not appearing - Android Studio

I have a NeutralButton that should cause an AlertDialog box I have to disappear. This issue is, when the AlertDialog box comes up, the text set appears just fine but the NeutralButton doesn't show at all. I tried it as a Positive and Negative button, but no difference was made. Here's the code:

Button infoG1;

infoG1 = (Button) findViewById(R.id.iG1);
infoG1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder info = new AlertDialog.Builder(game1.this);
info.setMessage("Text here");
info.show();
info.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});


}
});


I would have expected a button with text "Ok" to appear at the bottom of the AlertDialogue box, which causes the box to disappear once the user presses it. Would appreciate some help here, thanks in advance.

Answer

You shouldn't call setNeutralButton(...) before your show() method. You are doing this, which is causing the problem.

Instead of this:

dialog.show();
dialog.setNeutralButton(...);

Do this:

dialog.setNeutralButton(...);
dialog.show();

Note that you should put everything above your dialog.show(). Otherwise you will have problems.

Comments