【问题标题】:WebView in Fragment not loading page片段中的 WebView 未加载页面
【发布时间】:2016-08-15 16:15:49
【问题描述】:

我在 Fragment 的布局中添加了 WebView

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.deped.k12.GradeSheet"
    android:background="#fafafa">

    <!-- TODO: Update blank fragment layout -->

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

</FrameLayout>

但是当我尝试从中加载任何网站时。我只是得到一个空白的WebView

我尝试在 Android 监视器中查找错误消息,但没有。

这是我在 Fragment 中用于加载 URL 的代码:

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

        String url = "http://www.google.com/";
        WebView wv = (WebView)view.findViewById(R.id.webView);
        WebSettings settings = wv.getSettings();
        wv.setWebChromeClient(new WebChromeClient() {
        });
        final String mimeType = "text/html";
        final String encoding = "UTF-8";
        String html = "";
        settings.setJavaScriptEnabled(true);
        wv.loadDataWithBaseURL(url, html, mimeType, encoding, "");


        return view;
    }

我还添加了正确的权限:

这里可能有什么问题?

【问题讨论】:

    标签: android android-fragments webview


    【解决方案1】:

    以下代码适用于我:

    WebView webView = (WebView) view.findViewById(R.id.webView);
    webView.setWebViewClient(new WebViewClient());
    webView.getSettings().setJavaScriptEnabled(true);
    webView.loadUrl(url);
    

    我真的不知道你是否只需要添加一个 WebViewClient。

    更多信息:WebViewClient vs WebChromeClient

    【讨论】:

      【解决方案2】:

      你的问题是:

      String html = "";
      settings.setJavaScriptEnabled(true);
      wv.loadDataWithBaseURL(url, html, mimeType, encoding, "");
      

      您正在将空的 html 字符串加载到 web 视图中。

      尝试类似:wv.loadUrl("http://example.com/"); 或相应地更新您的 html 字符串。

      您应该查看loadDataWithBaseURL 方法的 API 文档。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-11-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-16
        • 1970-01-01
        • 1970-01-01
        • 2017-09-24
        相关资源
        最近更新 更多