我在使用 fragment 内的 WebView 时遇到问题。我在这一行收到一条错误消息,提示 “java.lang.nullpointerexception”:myWebView.setWebViewClient(new WebViewClient());。我用谷歌搜索了又用谷歌搜索,但没有找到解决方案。关于我缺少什么的任何想法?
fragment B.java
import android.annotation.SuppressLint;
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;
/**
* A simple {@link Fragment} subclass.
*
*/
@SuppressLint("SetJavaScriptEnabled")
public class FragmentB extends Fragment {
public FragmentB() {
// Required empty public constructor
}
private View mContentView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mContentView = inflater.inflate(R.layout.fragment_b, container, false);
WebView myWebView = (WebView)mContentView. findViewById(R.id.webView);
myWebView.setWebViewClient(new WebViewClient());
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("http://www.nellienova.com");
return mContentView;
}
}
webview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
最佳答案
确保您正在加载正确的 xml 文件。我之前通过错误地加载另一个布局文件来完成此操作。您在该文件上方键入了 webview.xml,但您膨胀了 R.layout.fragment_b
编辑
每个 fragment 都有自己的布局文件。您可以重用布局并将多个布局添加到一个 xml 文件,但通过代码,您的 fragment 只会扩充您引用的文件。
如果您想要包含其他文件,您必须先使用 include 语句将这些其他文件拉入您的 xml,然后才能与其他 xml 文件中的对象进行交互。点击here有关 include 语句的更多详细信息。下面的例子
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:background="@color/app_bg"
android:gravity="center_horizontal">
<include layout="@layout/titlebar"/>
<TextView android:layout_width=”match_parent”
android:layout_height="wrap_content"
android:text="@string/hello"
android:padding="10dp" />
</LinearLayout>
点击here有关 fragment 的一些有用信息。花点时间使用它,它将为您节省大量解决问题的时间。
关于android - fragment 内 webview 中的 Nullpointerexception,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24834957/