How to use Webview on an Alertdialog in Android

In this tutorial we will learn how to create a simple application that uses a button click to open an alert dialog box that contains a Webview.

This is important especially when there is need to display html content on an alertdialog in android. This tutorial will demonstrate how it can be achieved.

If you have not work with android Webview before or Alertdialog you can easily read it up in android official documentation also a little google search will provide the necessary materials for you.

Before we start we will create a new android project in Eclipse IDE. If you are using another IDE for android development just follow the instructions as shown here.

After you have created your project, add a button to the main activity you have created. On the MainActivity java file, attach a click event listener to the button so that when the button is click it will do something. For now we do not want to care much about what the button will do when it is click. Copy and paste the follow code in the onCreate callback method of your MainActivity java file

@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_button);		
		Button alertButton = (Button)findViewById(R.id.alert_button); 
		alertButton.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View view) {
			}
		});
	}

Right now when you click on the button it listens to a click event but it does not do anything. To achieve our purpose for this tutorial, we will now write the code that inserts an android Webview into an alert dialog. The code snippet is show below

@Override
protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstaneState);
     setContentView(R.layout.activity_button);
     Button alertButton = (Button) findViewById(R.id.alert_button);
     alertButton.setOnClickListener(new OnClickListener() {
                @Override
                 public void onClick(View view) {
		AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(ButtonActivity.this, 								R.style.full_screen_dialog));
		alert.setTitle("Solution to Question");
                WebView wv = new WebView(getApplicationContext());
		wv.getSettings().setBuiltInZoomControls(true);
		wv.setVerticalScrollBarEnabled(false);
		wv.setHorizontalScrollBarEnabled(false);
                wv.loadDataWithBaseURL(null, "HTML content here", "text/html", "utf-8", null);
		alert.setView(wv);
		alert.setNegativeButton("Close", new DialogInterface.OnClickListener() {
		@Override
		public void onClick(DialogInterface dialog, int id) {
		 dialog.dismiss();
                }
	 });
          alert.show();
	}
   });
}

 

Once you run the code you will see your html content in a Webview inside an alert dialog display.

If you have a question or suggestion, kindly use the comment box below.

Add a Comment