Alert dialogue title and message are not shown

2019-07-19 18:01发布

问题:

i created alert dialogue but title and message are not shown here is my code for alert dialogue

holder.add.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            AlertDialog.Builder builder;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                builder = new AlertDialog.Builder(context, android.R.style.Theme_Material_Dialog_Alert);
            } else {
                builder = new AlertDialog.Builder(context);
            }
            builder.setTitle("Alert");
            builder.setMessage("Are you sure")
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {

                        }
                    })
                    .setNegativeButton("No", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // User cancelled the dialog
                        }
                    });
            AlertDialog dialog = builder.create();
            dialog.show();
        }
    });

this is the screenshot of it

回答1:

Instead of context, try to use ActivityName.this.



回答2:

You have to pass theme as well in AlertBuilder.

AlertDialog.Builder myAlert = new AlertDialog.Builder(getContext(), R.style.AppCompatAlertDialogStyle);
deleteAlert.setTitle(title);
deleteAlert.setMessage(message);
deleteAlert.setPositiveButton(android.R.string.ok, clickListener);
deleteAlert.setNegativeButton(android.R.string.cancel, clickListener);
deleteAlert.show();

No need to call the create() method if you have called show(). Because internally the show() method calls create().

Note: I can clearly say the issue from my experience. I missed to pass theme.

R.style.AppCompatAlertDialogStyle

DOES NOT WORK:

AlertDialog.Builder myAlert = new AlertDialog.Builder(getContext());

WORKS SUCCESFULLY:

AlertDialog.Builder myAlert = new AlertDialog.Builder(getContext(),  R.style.AppCompatAlertDialogStyle);


回答3:

I don't know what is causing it, but for start I'm pretty sure you don't need to call builder.create() then dialog.show() separately.

Call directly builder.show() and let the Alert Dialog Builder handle its creation and display. If you really need the dialog instance, get it from the result of the builder.show().

About the lack of texts, maybe you are overriding some style, have you checked if the texts are simply White colored and because of that are "invisible"?