我收到错误时无法解析方法'findViewById(int)' 调用webview,如何解决这个问题? 实际上这个webview是我家的片段(程序的第一个片段)
package com.fb.jaisonjoseph.facebookbasic;
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.WebView;
/**
* A simple {@link Fragment} subclass.
*/
public class Home_Fragment extends Fragment {
public WebView mwebView;
public Home_Fragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
WebView view=(WebView) findViewById(R.id.webView);
view.loadUrl("http://google.com");
view.getSettings().setJavaScriptEnabled(true);
view.setWebViewClient(new MyWebViewClient());
return inflater.inflate(R.layout.fragment_home_, container, false);
}
}
答案 0 :(得分:3)
问题
1。)您每次都会返回一个新视图
return inflater.inflate(R.layout.fragment_home_, container, false);
2.。)使用膨胀的视图来查找您的观点
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view =inflater.inflate(R.layout.fragment_home_, container, false);
// ^^^ will have all view of fragment_home_ layout
WebView webView = (WebView) view.findViewById(R.id.webView);
// ^^^^ use view to find your webview
webView.loadUrl("http://google.com");
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new MyWebViewClient());
return view;
}
注意:您可以从mwebView
课程中删除Home_fragmnet
,但如果您想在其他方法中使用您的网页视图,请使用mwebView
代替本地WebView view
变量
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view =inflater.inflate(R.layout.fragment_home_, container, false);
// ^^^ will have all view of fragment_home_ layout
mwebView = (WebView) view.findViewById(R.id.webView);
//^^^ use global variable instead of creating a local one
mwebView.loadUrl("http://google.com");
mwebView.getSettings().setJavaScriptEnabled(true);
mwebView.setWebViewClient(new MyWebViewClient());
return view;
}
答案 1 :(得分:2)
使用这种方式。
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_home_, null);
WebView view=(WebView) rootView.findViewById(R.id.webView);
view.loadUrl("http://google.com");
view.getSettings().setJavaScriptEnabled(true);
view.setWebViewClient(new MyWebViewClient());
return rootView;
}
答案 2 :(得分:0)
您必须使用以下代码行:
WebView view=(WebView) getActivity().findViewById(R.id.webView);
而不是
WebView view=(WebView) findViewById(R.id.webView);
这是因为findViewById()
无法直接在Fragment
上调用。您要么必须参考Acticity,要么在View
- 对象