If you want to show a WebView
component in an Android AlertDialog
, the following method shows how to do it:
private void handleInfoButtonPressed() { DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int choice) { switch (choice) { case DialogInterface.BUTTON_NEUTRAL: break; } } }; // create a WebView with the current stats WebView webView = new WebView(context); webView.loadData(SampleStats.boxScore1, "text/html", "utf-8"); // display the WebView in an AlertDialog AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("Stats (Sample)") .setView(webView) .setNeutralButton("OK", dialogClickListener) .show(); }
In that code, SampleStats.boxScore1
is a long HTML String
that I use to show some statistics in my application. The resulting AlertDialog
with the WebView
looks like this in an Android emulator:
(Sorry, the alignment of the title and OK button currently look horrible with the WebView
content.)
The short version of the solution
If you know Android, the only code you really need to see for this solution are these lines of code:
// create a WebView WebView webView = new WebView(context); // populate the WebView with an HTML string webView.loadData(SampleStats.boxScore1, "text/html", "utf-8"); // create an AlertDialog.Builder AlertDialog.Builder builder = new AlertDialog.Builder(context); // set the WebView as the AlertDialog.Builder’s view builder.setView(webView);
Accessing a URL
I’m sure that most developers will want to access an internet URL rather than using an HTML string with a WebView
, so for the sake of completeness, this is how you access a URL with an Android WebView
:
WebView webView = new WebView(context); webView.loadUrl("http://www.google.com/");
Then you can put the WebView
in an AlertDialog.Builder
. Here’s a slightly different approach to doing that:
WebView webView = new WebView(context); webView.loadData("<p>No help for you!</p>", "text/html", "utf-8"); AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("Help") .setView(webView) .setNeutralButton("OK", null) .show();
Summary
In summary, if you want to show a WebView
component with an Android AlertDialog.Builder
, I hope the source code in these examples is helpful.