Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GridView getChildAt() returns null

I'm trying to get a View from GridView. Unfortunately, it returns null.

onCreate():

GridView gridview = (GridView) findViewById(R.id.gridView);
gridview.getChildAt(3).setBackgroundResource(R.drawable.list_selector_holo_light);

gridview.getChildCount() returns 0 too!

What can I do to get this View? I know that there is an option to change the background in the Adapter, but I have to do it dynamically.

Thanks for help!


EDIT

setAdapter:

gridview.setAdapter(new ImageAdapter(this));

ImageAdapter:

public View getView(int position, View convertView, ViewGroup parent) {
    final ImageView imageView;
    if (convertView == null) {  // if it's not recycled, initialize some attributes
        imageView = new ImageView(mContext);
        imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setPadding(8, 8, 8, 8);
    } else {
        imageView = (ImageView) convertView;
    }

    imageView.setImageResource(mThumbIds[position]);
    return imageView;
}
like image 995
Dennis Avatar asked Dec 26 '22 06:12

Dennis


1 Answers

GridView will populate itself from the adapter during the first layout pass. This means it won't have children in onCreate(). The easiest way to wait for the first layout pass is to use a ViewTreeObserver (see View.getViewTreeObserver()) to register a global layout listener. The first time the listener is invoked, the grid should contain children.

Note that if you want to change the background of one of the children of a GridView you really should do it from the adapter. Since views are recycled the background may appear to "move" to another view later on.

like image 186
Romain Guy Avatar answered Jan 05 '23 17:01

Romain Guy