最近我开始使用 WebView 创建一个 Android 应用程序。该应用程序已经发展壮大,我将使用 WebView 的 Activity 更改为使用 fragment 和 ViewPager 的选项卡式 Activity 。然后开始了我的问题。经过一些头痛之后,我终于设法为每个选项卡显示正确的 fragment 。然后我只是将 WebView 的代码复制到其中一个 fragment ,但该 fragment 没有显示我想要的网页。任何帮助将不胜感激!
代码如下:
带有 webView 的 fragment
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>
最佳答案
喜欢做的事情
@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;
}
关于android - 在 Fragment 中使用 WebView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31159149/