最近我开始用WebView创建一个Android应用程序。应用程序已经增长,我使用片段和ViewPager将WebView的活动更改为选项卡式活动。我的问题开始了。经过一番头痛之后,我终于设法了如何为每个标签显示正确的片段。然后我只是将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>
答案 0 :(得分:36)
要做的事情
@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;
}