AlbaStar AlbaStar - 4 months ago 23
Java Question

Displaying webview on blank fragment

I have 3 fragments, in each of them, I like to display the

WebView
of different URLs.

Example for fragment 1, on my xml file I added:

<WebView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/webView"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true" />


But in my java file i have this:

package com.domain.app;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;


/**
* A simple {@link Fragment} subclass.
*/
public class Fragment_Home extends Fragment {


public Fragment_Home() {
// Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false);

}

}


I got the below code from another android project:

myWebView = (WebView)findViewById(R.id.webView);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("http://www.google.com");
myWebView.setWebViewClient(new WebViewClient());


which was in
MainActivity
, but how to put this code to my fragment?

Answer

Since you are doing this in a fragment you need to expand and reference the view that your webview will live in. So change your onCreate to this:

WebView myWebView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    //creating and referencing our View
    View view = inflater.inflate(R.layout.fragment_home,container,false);

    //The key difference is we reference our view with the findViewById
    myWebView = (WebView) view.findViewById(R.id.webView);
    WebSettings webSettings = myWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    myWebView.loadUrl("http://www.google.com");
    myWebView.setWebViewClient(new WebViewClient());

    return view;
}

Here you can see that I changed it to actually reference the view you are pulling from which will allow you to update the components of that view. When manipulating components of a fragment you always need to reference the parent view.

Comments