Android: using a TextView to show rich text in an AlertDialog

If you want to display a link or basic formatting in an AlertDialog on Android, you can do it by providing HTML.

The key parts you need are Html.fromHtml and TextView.setMovementMethod.

Make sure you pass the dialog’s context in to the constructor of the TextView, not the context of the current activity. Otherwise the colours in your TextView will be wrong and you may well end up with black text on a dark grey background.

AlertDialog dialog = new AlertDialog.Builder( activity )
    .setTitle( t( world.name ) )
    .setPositiveButton( "Yes!" )
    .setNeutralButton( "Maybe?" )
    .create();

TextView view = new TextView( dialog.getContext() );
view.setText( Html.fromHtml( "<b>foo</b> <a href='#'>bar</a>" ) );
view.setMovementMethod( LinkMovementMethod.getInstance() );
view.setPadding( 10, 10, 10, 10 );

dialog.setView( view );
dialog.show();

If you are on API level 11+, you can use AlertDialog.Builder’s getContext() method, so you don’t have to create the dialog until the end.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.