Simple android showDialog example

  Uncategorized

A dialog can have a custom layout with buttons, text views, list, images, checkboxes, etc. You can create a layout for your dialog and show the dialog with the following simple method.

The showDialog method can be a part of your activity class. In that case you don’t need to explicitly declare the context as parameter. Just use this in case of context in the method body.

public void showDialog(Context context, String title, String message)
{
    final Dialog dialog = new Dialog(context);
    dialog.setContentView(R.layout.custom_dialog_layout);
    dialog.setTitle(text);
    TextView messageBox = (TextView ) dialog.findViewById(R.id.dialog_message);
    messageBox.setText (message);
    Button dialogButton = (Button) dialog.findViewById(R.id.dialog_button_ok);
    dialogButton.setOnClickListener(new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            // do something here when ok is pressed
            dialog.dismiss();
        }
    });
    dialog.show();
}

Tha lyout filename is dialog_message.xml in this example.


       
    
    

You need to use HTML in your message. Simply referencing a String with HTML in your messageBox will not work. If you want to show html formated text in your dialog, you can use the following method to set the text of your text view.

    messageBox.setText (Html.fromHtml(message));

The following HTML tags are supported By TextView:


, , , 
,
, , ,
, , ,

,

,

,

,

,
, , ,

, , , , , , ,

Alternatively, you can use the great HTMLDialog library for you html dialog. (https://github.com/msoftware/HtmlDialog). The HtmlDialog lib simplifies the display of HTML in a DialogFragment. It is useful for displaying Open Source Licenses, EULAs, Terms of Service pages, etc.

The HTMLDialog is licensed under the Apache License, Version 2.0