2

我在 onCreateView 的片段中设置了一个 gridview 来显示星期几,如下所示:

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);

我使用的指定 R.layout.event_gridview_header_cell 的单元格布局如下:

<?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>

在片段的 onStart 方法中,我尝试使用以下方法突出显示特定单元格:

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

不幸的是,getChildAt 方法总是返回 null。如果我查询gridview,我发现它是可见的,但它没有孩子。网格视图在屏幕上清晰可见,并填充了正确的值。

在此先感谢您的帮助!

4

1 回答 1

3

您必须覆盖getView(...)适配器的方法。尝试这样做:

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;
    };
}
于 2013-10-18T13:42:09.970 回答