Android Rich Dialogs

Rich Dialogs are easyDisplaying text to the user with Android’s DialogBuilder is easy to use and gets the job done. But what if you want to spice it up a little with some fancy text and styling? You can by embedding a webview in the dialog. Here’s how:

Start by creating your dialog’s html file and put it in your project’s /res/raw folder (if your project does not already have the raw folder create one now). Be careful what you name the html file, as it is a compiled android resource, it must follow the android resource naming and can only contain the characters [a-z0-9_-.].

Put these two utility functions somewhere:

public static void createHTMLDialog(Context context, String title, int resourceId) throws IOException { AlertDialog.Builder dbuilder = new AlertDialog.Builder(context); WebView wv = new WebView(context); String htmlString = StringUtil.loadRawResourceString(context.getResources(), resourceId); wv.loadDataWithBaseURL(null, htmlString, "text/html", "utf-8", null); dbuilder.setView(wv); dbuilder.setTitle(title); dbuilder.setPositiveButton("OK", null);; } public static String loadRawResourceString(Resources res, int resourceId) throws IOException { StringBuilder builder = new StringBuilder(); InputStream is = res.openRawResource(resourceId); InputStreamReader reader = new InputStreamReader(is); char[] buf = new char[1024]; int numRead=0; while(( != -1){ builder.append(buf, 0, numRead); } return builder.toString(); }

Finally, when you want to display the rich dialog to the user use something like this:

createHTMLDialog(getContext(), "Hello World", R.raw.hello);


Paul Soucy

Read more posts by this author.