【问题标题】:Using WebView in Fragment在 Fragment 中使用 WebView
【发布时间】:2015-09-18 11:34:28
【问题描述】:

最近我开始使用 WebView 创建一个 Android 应用程序。该应用程序已经增长,我将使用 WebView 的活动更改为使用片段和 ViewPager 的选项卡式活动。我的问题开始了。经过一些头痛后,我终于设法为每个选项卡显示正确的片段。然后我只是将 WebView 的代码复制到其中一个片段,但片段没有显示我想要的网页。任何帮助将不胜感激!

代码如下:

带有 webView 的片段

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.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class WebViewFragment extends Fragment {

    public WebView mWebView;

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

        mWebView = (WebView) mWebView.findViewById(R.id.webview);
        mWebView.loadUrl("google.com");

        // Enable Javascript
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        // Force links and redirects to open in the WebView instead of in a browser
        mWebView.setWebViewClient(new WebViewClient());

        return inflater.inflate(R.layout.fragment_bugtracker, container, false);
    }
}

和xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".Tabs$BugtrackerFragment">

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

【问题讨论】:

  • @Duggu 这是怎么复制的?

标签: android android-fragments webview


【解决方案1】:

喜欢做的事

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

    View v=inflater.inflate(R.layout.fragment_bugtracker, container, false);
    mWebView = (WebView) v.findViewById(R.id.webview);
    mWebView.loadUrl("https://google.com");

    // Enable Javascript
    WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);

    // Force links and redirects to open in the WebView instead of in a browser
    mWebView.setWebViewClient(new WebViewClient());

    return v;
}

【讨论】:

  • 很好,但我不明白一件事,为什么定义和返回 v 不是仅仅返回它的定义?
  • 'v' 在这里表示膨胀的视图。那是用户定义的变量。
猜你喜欢
  • 2016-03-19
  • 1970-01-01
  • 2018-09-13
  • 2013-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多