我想实现GridView,每个单元格都包含一个类对象。为此,我实现了片段类:
public class DayUC extends Fragment {
/*
some variables
*/
// use to create instance of class with initial parameters
public static DayUC newInstance(//initial parameters) {
DayUC dayUC = new DayUC();
/*
set parameters
*/
return dayUC;
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_layout, container, false);
initialization() //initial variables and view elemans (textView, ...)
return rootView;
}
}
我也创建了GridViewAdapter:
public class GridViewAdapter extends BaseAdapter {
private ArrayList<DayUC> gridList; //list of grid DayUC objects
Context context;
public GridViewAdapter(Context context, ArrayList<DayUC> gridList) {
this.gridList = gridList;
this.context = context;
}
@Override
public int getCount() {
return gridList.size();
}
@Override
public DayUC getItem(int position) {
return gridList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
return gridList.get(position).getView();
}
}
但是当我创建GridView时,它会抛出NullPointerException!我发现在gridView元素(DayUC)中 onCreateView()从未调用过。所以 gridList.get(position).getView()返回null !!
有谁可以帮我解决这个问题?我怎么能强制 onCreateView 被调用?
修改:添加了MainActivity onCreate方法:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DayUC[] dayUC = new DayUC[42];
monthGridView = (GridView) findViewById(R.id.month_view);
for (int i = 0; i < 42; i++) {
dayUC[i] = DayUC.newInstance(//inpute arguments)
dayUCList.add(dayUC[i]);
monthCal.add(Calendar.DATE, 1);
}
gridViewAdapter = new MonthGridViewAdapter(getActivity(), dayUCList);
monthGridView.setAdapter(gridViewAdapter);
gridViewAdapter.notifyDataSetChanged();
}