Skip to content Skip to sidebar Skip to footer

Android - Displaying Webview In Fragment

So I have a fragment with the following in the XML layout file: Copy

Solution 2:

Below is the xml for fragment:

<?xml version="1.0" encoding="utf-8"?><RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".WebActivity"><WebViewandroid:layout_width="match_parent"android:layout_height="wrap_content"android:id="@+id/webview"></WebView></RelativeLayout>

And try this for fragment class

publicclassMainFragmentextendsFragment {

WebView webView;

publicMainFragment() {

}

@OverridepublicvoidonActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    webView=(WebView)getActivity().findViewById(R.id.webview);
    WebSettings webSettings=webView.getSettings();
    webSettings.setJavaScriptEnabled(true);

    webView.loadUrl("your_url");

    webView.setWebViewClient(newMybrowser());

    if (savedInstanceState != null)
        webView.restoreState(savedInstanceState);
    else
        webView.loadUrl("your_url");
}

privateclassMybrowserextendsWebViewClient {
    @OverridepublicbooleanshouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        returntrue;
    }
}

@OverridepublicViewonCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragmentreturn inflater.inflate(R.layout.fragment_main, container, false);
}
}

Solution 3:

@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragmentreturn inflater.inflate(R.layout.fragment_main, container, false);


        Stringurl="http://winn-brown.co.uk/";
        WebViewwv= (WebView) view.findViewById(R.id.webView);
        wv.setWebViewClient(newWebViewClient());
        wv.getSettings().setJavaScriptEnabled(true);
        wv.loadUrl(url);
    }

Post a Comment for "Android - Displaying Webview In Fragment"