Home » Android » android – How to build alert dialog with a multi-line title?

android – How to build alert dialog with a multi-line title?

Posted by: admin June 15, 2020 Leave a comment

Questions:

Is it possible to have a multi-line title in an Android alert dialog? I tried a couple of solutions posted here but none worked for me. I always end up with the title showing 3 dots (…) string for title.
Any sample code or working example regarding the same would be highly appreciated.

How to&Answers:

If you are using alert dialog then title can contain maximum 2 line, else you have to go with custom Dialog.

Answer:

You need to use builder.setCustomTitle():

AlertDialog.Builder builder = new AlertDialog.Builder(context);
TextView textView = new TextView(context);
textView.setText("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur " +
                "tincidunt condimentum tristique. Vestibulum ante ante, pretium porttitor " +
                "iaculis vitae, congue ut sem. Curabitur ac feugiat ligula. Nulla " +
                "tincidunt est eu sapien iaculis rhoncus. Mauris eu risus sed justo " +
                "pharetra semper faucibus vel velit.");
builder.setCustomTitle(textView);

Documentation is here: AlertDialog.builder

enter image description here

Answer:

This is the way to set title

AlertDialog.Builder builder = new  AlertDialog.Builder(Class name.this);
    builder.setTitle("Welcome to App,\n There are no App.\n Add a new data.");

Answer:

Actually the “correct” answer here is wrong. It turns out you can set maximum lines to more than 2 in AlertDialog. Here is an example:

AlertDialog closePlayerDialog;
.........
Builder builder = new AlertDialog.Builder(this);
builder.setMessage(getString(R.string.AskToClosePlayer))
       .setPositiveButton(R.string.Yes, dialogClickListener)
       .setNeutralButton(R.string.NoJustCloseApp, dialogClickListener)
       .setNegativeButton(R.string.NoContinue, dialogClickListener);
closePlayerDialog = builder.create();
closePlayerDialog.setOnShowListener(new DialogInterface.OnShowListener() {
    public void onShow(DialogInterface dialog) {
        float textSize = 12.0f;
        Button positive = closePlayerDialog.getButton(AlertDialog.BUTTON_POSITIVE);
        positive.setTextSize(TypedValue.COMPLEX_UNIT_DIP, textSize);
        positive.setMaxLines(3);
        Button neutral = closePlayerDialog.getButton(AlertDialog.BUTTON_NEUTRAL);
        neutral.setTextSize(TypedValue.COMPLEX_UNIT_DIP, textSize);
        neutral.setMaxLines(3);
        Button negative = closePlayerDialog.getButton(AlertDialog.BUTTON_NEGATIVE);
        negative.setTextSize(TypedValue.COMPLEX_UNIT_DIP, textSize);
        negative.setMaxLines(3);
    }
});
closePlayerDialog.setCancelable(false);     
closePlayerDialog.show();

Basically you edit the AlertDialog’s components onShow, using DialogInterface.onShowListener.