user2864826
user2864826

Reputation: 27

Issue Loading a webview within a dialog

I am trying to load a webview within a dialog.But the webview never displays.I have store the html file in the raw folder. I only get a dialog having the title.Any suggestions would be helpful.

public class MainActivity extends Activity
 {
    String linewise="";
    final Context context=this;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); 

    Button button=(Button)findViewById(R.id.button);    


    button.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            final Dialog dialog=new Dialog(context);
            dialog.setContentView(R.layout.dialog_webview);
            dialog.setTitle("WebView");

            WebView webview=(WebView)dialog.findViewById(R.id.webview);
            webview.getSettings().setJavaScriptEnabled(true);
            webview.loadUrl("file:///android_res/raw/abc.htm"); 
            dialog.show();  


        }


    });
    }   

}

XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <WebView 
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>

Upvotes: 0

Views: 254

Answers (2)

MFP
MFP

Reputation: 1141

Here is my code for loading webview inside dialog, it is working fine for me. put your html file inside assets folder.

         AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this); 
         alert.setTitle("Title here");

            WebView wv = new WebView(MainActivity.this);
            wv.getSettings().setJavaScriptEnabled(true);
            wv.loadUrl("file:///android_asset/myhtml.html");
            alert.setView(wv);
            alert.setNegativeButton("Close",new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                dialog.dismiss();
            }
        });


         alert.show();

Please accept & try this code.it is definitely work for you.

Upvotes: 1

user2864826
user2864826

Reputation: 27

Changing the layout_height to wrapcontent fixed it.

Upvotes: 0

Related Questions