ttempt在空对象引用上调用虚方法'android.view.View android.view.View.findViewById(int)'

时间:2016-07-21 09:53:08

标签: android findviewbyid

我创建了一个Fragment,我想加载一个WebView。但是我得到了这个错误:

    public class StudentPlanFragment extends Fragment {

    private WebView mWebView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View onCreateView = super.onCreateView(inflater, container, savedInstanceState);

        mWebView = (WebView) onCreateView.findViewById(R.id.webViewStudentPlan);
        mWebView.loadUrl("http://example");
        mWebView.getSettings().setJavaScriptEnabled(true);


        return onCreateView;
    }
}

守则:

grails install-plugin codenarc

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

编辑如下:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.YOUR_LAYOUT_NAME, null);
mWebView = (WebView) rootView .findViewById(R.id.webViewStudentPlan);
mWebView.loadUrl("http://example");
mWebView.getSettings().setJavaScriptEnabled(true);


return rootView ;
}

答案 1 :(得分:1)

您必须在代码中对xml进行充气,才能从xml布局中找到WebView

public class StudentPlanFragment extends Fragment {

private WebView mWebView;

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

    //Delete the below commented code, it is just to highlight the mistake in the existing code

    /* View onCreateView = super.onCreateView(inflater, container, savedInstanceState);*/

    View mView = inflater.inflate(R.layout.YOUR_XML_LAYOUT_FILE_NAME, container, false);

    mWebView = (WebView) onCreateView.findViewById(R.id.webViewStudentPlan);
    mWebView.loadUrl("http://example");
    mWebView.getSettings().setJavaScriptEnabled(true);


    return onCreateView;
    }
}