Search code examples
androidandroid-gridview

getChildAt always returns null


I've set up a gridview in a fragment in onCreateView to display days of the week as follows:

weekGridView = (GridView)view.findViewById(R.id.weekGrid);

// set up days of week grid
dayAdapter = new ArrayAdapter<String>(ShowEventsNavFragment.this.getActivity(), R.layout.event_gridview_header_cell, R.id.cellTextView, days);
headerGrid.setAdapter(dayAdapter);

The cell layout I'm using designated R.layout.event_gridview_header_cell is as follows:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/cellTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:gravity="center"
        android:textStyle="bold"
        android:textSize="18sp" />

</RelativeLayout>

In the fragment's onStart method, I am trying to highlight a particular cell using:

int highlightDay = cal.get(Calendar.DAY_OF_WEEK);
RelativeLayout rl = (RelativeLayout)weekGridView.getChildAt(highlightDay);
rl.setBackgroundColor(0x448FCC85);

Unfortunately, the getChildAt method always returns null. If I query the gridview, I find that it is visible, but that it has no children. The gridview is clearly visible on the screen and populated with the correct values.

Thanks in advance for your help!


Solution

  • You have to override the getView(...) method of your adapter. Try to do this:

    dayAdapter = new ArrayAdapter<String>(getActivity(), R.layout.event_gridview_header_cell, R.id.cellTextView, days) {
        public View getView(int position, View convertView, android.view.ViewGroup parent) {
            View result = super.getView(position, convertView, parent);
            int highlightDay = cal.get(Calendar.DAY_OF_WEEK)
            // if I am right with indexing ...
            if(position == highlightDay - 1) {
                result.setBackgroundColor(0x448FCC85);
            } else {
                // set another background ... this is the default background, you have to provide this because the views are reused
            }
            return result;
        };
    }