Anton Gildebrand Anton Gildebrand -4 years ago 72
Android Question

Inflating view from within instance not working

I'm creating an adapter that should populate a GridView with images of cars, and a model name. I have created a grid item as an own XML-file, with the desired widgets (ImageView and TextView). However, I can't seem to inflate the view from within my

instance. It works if I inflate the view from the
-method of my adapter however.

What happens if I inflate the view from within the
instance, is that I can't see the view that's supposed to be inflated.

Below is my

public class CarsGridViewItem extends RelativeLayout {

private Car car;

private ImageView carImg;
private TextView nameTxt;

public CarsGridViewItem(Car car, Context context) {
super(context); = car;

inflate(getContext(), R.layout.fragment_cars_grid_item, this);

private void findViews() {
this.carImg = (ImageView)findViewById(;
this.nameTxt = (TextView)findViewById(;

private void setupViews(){;

public void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
super.onMeasure(widthMeasureSpec, widthMeasureSpec);

protected void onLayout(boolean b, int i, int i1, int i2, int i3) {


And the
-method of my adapter

public View getView(int position, View convertView, ViewGroup parent){
return new CarsGridViewItem(cars.get(position), mContext);

/* The code below works!

LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout view = (RelativeLayout) inflater.inflate(R.layout.fragment_cars_grid_item, null);

ImageView carImg = (ImageView)view.findViewById(;

TextView nameTxt = (TextView)view.findViewById(;

return view;*/

I'm doing something wrong here, but I can't seem to figure out what. All the examples I've found on the topic of inflating views does it like this!

Answer Source

Either remove onMeasure() and onLayout() methods from CarsGridViewItem or implement them correctly, because you do not override them correctly now.

You have overriden onLayout() and are doing nothing there, thus nothing is being laid out. Let the super class layout the view for you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download