我在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,我发现它是可见的,但它没有子节点。网格视图在屏幕上清晰可见,并填充正确的值。
提前感谢您的帮助!
答案 0 :(得分: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;
};
}