Android: using a TextView to show rich text in an AlertDialog
October 10, 2015 [Android, Programming, Tech]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.