Francis Ndirangu
Francis Ndirangu

Reputation: 19

How to add use web view on a fragment file?

How can I call a WebView on my fragment?
As you can see I have called it, but I am having an error. What I want to implement is a webpage to open on my application.

Here's the code I'm using:

package sampleapp.razen.com.sampleapp;


import android.app.FragmentTransaction;
import android.os.Bundle;
import android.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 GeoNjoroFragment extends Fragment {


    public GeoNjoroFragment() {

        // Required empty public constructor
    }



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

        View view = inflater.inflate(R.layout.fragment_geo_njoro, container, false);

        WebView myWebView = (WebView)view.findViewById(sampleapp.razen.com.sampleapp.R.id.webview);
        myWebView.getSettings().setLoadsImagesAutomatically(true);
        myWebView.getSettings().setJavaScriptEnabled(true);
        myWebView.getSettings().setDomStorageEnabled(true);
        myWebView.getSettings().setBuiltInZoomControls(true);
        myWebView.getSettings().setSupportZoom(true);
        myWebView.loadUrl("http://www.google.com/");
// Inflate the layout for this fragment
        return view;

    }



}

Here's an image of the error I'm receiving:

Image of Error

Upvotes: 0

Views: 578

Answers (2)

Riven
Riven

Reputation: 3

U don't bind the view so that webview can't find the view to bind, it should be:

View view = inflater.inflate(R.layout.fragment_geo_njoro, container, false); WebView myWebView = (WebView)view.findViewById(sampleapp.razen.com.sampleapp.R.id.webview);

Upvotes: 0

Kush Patel
Kush Patel

Reputation: 1251

Try this code. First of all you have to inflate your view and then use findViewById() method. Add this permission uses-permission android:name="android.permission.INTERNET" to Androidmanifest.xml file.

    View view = inflater.inflate(R.layout.fragment_geo_njoro, container, false);

    WebView myWebView = (WebView)view.findViewById(sampleapp.razen.com.sampleapp.R.id.webview);
        myWebView.getSettings().setLoadsImagesAutomatically(true);
        myWebView.getSettings().setJavaScriptEnabled(true);
        myWebView.getSettings().setDomStorageEnabled(true);
        myWebView.getSettings().setBuiltInZoomControls(true);
        myWebView.getSettings().setSupportZoom(true);
        myWebView.loadUrl("http://www.hivisasa.com/wb/nakuru/news/113249");
// Inflate the layout for this fragment
return view;

Upvotes: 2

Related Questions