4

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;
}
Dennis
  • 2,271
  • 6
  • 26
  • 42

1 Answers1

10

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.

Romain Guy
  • 97,993
  • 18
  • 219
  • 200
  • It's working now! Thank you very much! I need to change the background in the activity instead of the adapter, because this is depends on somethings in the activity (what the user chooses). If you have more efficient way then I have done, I would like to hear that. Thank you again! – Dennis Apr 05 '13 at 17:34
  • Is there a way to 'fake' a layout pass? Because GridView is limited as a RemoteView I want to keep an internal one in my RemoteViewService that generates a good looking view then use the getDrawingCache method and just set an imageview in the remote gridview. Unfortunately gridView.getChildAt always returns null because its not actually attached to the screen. – Nathan Schwermann Apr 08 '14 at 21:55