Search code examples
androidwebviewandroid-fragments

implement webview on fragment


I'm trying to implement webview on a fragment. I'm using this with backwards compatibility (support.v4.app) so I can't extend to WebViewFragment.

I'm starting with fragments and I've never used Webview, si I'm not very sure of how is this programed.

This is my layout web_view.xml:

<LinearLayout 
xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" 
android:baselineAligned="false">

<WebView
        android:id="@+id/webview_container"
        android:layout_width="fill_parent"        
        android:layout_height="fill_parent" />    

And this is the WebView class:

public class WebView extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View mainView = inflater.inflate(R.layout.web_view, container, false);

        WebView webView = (WebView) mainView.findViewById(R.id.webview_container);  ERROR 1
        webView.getSettings().setJavaScriptEnabled(true);  //ERROR 2
        webView.setWebViewClient(new SwAWebClient());  //ERROR 3
        webView.loadUrl("http://maps.google.com");  //ERROR 4

    return mainView;
}

ERROR 1: Cannot cast from view to webview

ERROR 2: The method getSettings() is undefined for the type WebView

ERROR 3: The method setWebViewClient() is undefined for the type WebView

ERROR 4: The method loadUrl() is undefined for the type WebView


Solution

  • Your class has the same name as android.webkit.WebView. Rename your fragment name or try

    android.webkit.WebView webView = (android.webkit.WebView) mainView.findViewById(R.id.webview_container);