对于Fragment02类型,方法findViewById()未定义

时间:2014-05-28 06:29:36

标签: android android-fragments

我在尝试按照我一直以来的方式创建WebView时遇到错误,说

  

对于Frament02

类型,方法findViewById()未定义

为什么?我已经读过我可以使用该方法引用父活动,但我不确定我的ActivitiesFragment是否正在使用它?

public class Fragment02 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_02, container, false);


            WebView myWebView = (WebView) findViewById(R.id.webView1);

2 个答案:

答案 0 :(得分:2)

试试这种方式

@Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
 View v= inflater.inflate(R.layout.fragment_02, container, false);
 WebView myWebView = (WebView) v.findViewById(R.id.webView1);
 return v;
}

您应该从Views夸大的视图中引用Fragment

答案 1 :(得分:1)

更改为

View view = inflater.inflate(R.layout.fragment_02, container, false);
WebView myWebView = (WebView)view. findViewById(R.id.webView1);
return view.

夸大布局。使用视图对象初始化fragment_02.xml中的视图。

http://developer.android.com/reference/android/view/View.html#findViewById%28int%29

或者,您可以return View onCreateViewonActivityCreated使用getView().findViewById()初始化视图。