user3455532
user3455532

Reputation:

The method findViewById() is undefined for the type Fragment02

I'm getting an error when trying to create a WebView the way I always do, saying

The method findViewById() is undefined for the type Frament02

How come? I've read that I could refer to a parent activity using that method but I'm not sure if any of my Activities or Fragments is using it?

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);

Upvotes: 0

Views: 124

Answers (2)

Raghunandan
Raghunandan

Reputation: 133560

Change to

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

Inflate the layout. Use the view object to initialize views in fragment_02.xml.

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

Alternatively you can just return View in onCreateView and in onActivityCreated use getView().findViewById() to initialize views.

Upvotes: 1

M D
M D

Reputation: 47817

try this way

@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;
}

You should reference your Views from your Fragment inflated view.

Upvotes: 2

Related Questions