findViewById in Android fragments

A quick post on how to add and set android widget behavior in a fragment implementation. Fragments in android don’t extend Activity but Fragment. This implies that your standard way of referring to android widgets won’t work e.g. Button btn = (Button)findViewById(R.id.btn1);When you try this implementation you wil notice that the Android SDK wont recognize your code, this is because you extended Fragments instead of Activity. Changing your extend to Activity would not solve it ;)

It took me a few hours to actually solve this, and I couldn’t find many resources online, so I would share the solution in this small blog post. It’s actually pretty simple.

In my example I use an ImageView with an OnClicklistener launching a browser website.

The solution is to put your widget reference with small adjustment (myFragmentView.findViewbyId) together with e.g. the Intent within your Fragment inflation.

package com.christianpeeters.historymaatstricht;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

public class FragCityhall extends Fragment {
	

 @pOverride
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
   Bundle savedInstanceState) {
	 
	 
	 
  View myFragmentView = inflater.inflate(R.layout.frag_cityhall, container, false);
  
  ImageView maps = (ImageView) myFragmentView.findViewById(R.id.ivcityhallmaps);
  maps.setOnClickListener(new View.OnClickListener() {
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent intent = new Intent(android.content.Intent.ACTION_VIEW, 
				Uri.parse("http://www.nu.nl"));
				startActivity(intent);
	}
}) ;
  
  
  return myFragmentView;

 }

}

2 Responses

  1. wig January 8, 2013 / 6:33 pm

    hello That’s a good post.

  2. Peter January 22, 2013 / 10:46 pm

    Great idea – you could also override onActivityCreated and simply access the view elements using getView().findViewById(…)

Leave a Reply to wig Cancel reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*