Tuesday, June 4, 2013

Webview in Dialog

If you want to show webview in a dialog, use the following code snippet-


private void showWebviewInDialog(){
  Context mContext = getActivity();
  AlertDialog.Builder alert = new AlertDialog.Builder(mContext);

  alert.setTitle("Pay your premium");
  WebView wv = new WebView(mContext);

                  //Required else page would open in browser
  wv.setWebViewClient(new MyWebViewClient());

                  //To load HTML
  //String html = "<html><body>some html here</body></html>";
                  //wv.loadData(html, "text/html", "UTF-8");

                  //To load URL
  wv.loadUrl("https://www.billjunction.com");
  alert.setView(wv);
  alert.setIcon(R.drawable.icon);
  alert.setPositiveButton("Pay", new DialogInterface.OnClickListener(){
    public void onClick(DialogInterface dialog, int id){
        Toast.makeText(getActivity(), "Success", Toast.LENGTH_SHORT).show();
    }
  });
  alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
    public void onClick(DialogInterface dialog, int id){
       Toast.makeText(getActivity(), "Fail", Toast.LENGTH_SHORT).show();
    }
  });
  alert.show();
}

private class MyWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
       
        return false;
    }
}