我有以下类扩展片段:
public static class DummySectionFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
private GridView events;
public DummySectionFragment() {}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle args = getArguments();
switch (args.getInt(ARG_SECTION_NUMBER)) {
case 1 : return initializeCalendarScreen(inflater);
case 2 : return inflater.inflate(R.layout.todo_lists_layout, null);
}
return null;
}
public void updateGridView() {
int daysInCurrentMonth=(MainActivity.month==1) ? daysInFebruary : COUNT_OF_DAYS_IN_MONTH[MainActivity.month];
int daysInPrevMonth=(MainActivity.month-1==1) ? daysInFebruary : COUNT_OF_DAYS_IN_MONTH[MainActivity.month-1];
int daysInNextMonth=(MainActivity.month+1==1) ? daysInFebruary : COUNT_OF_DAYS_IN_MONTH[MainActivity.month+1];
Calendar calendar=Calendar.getInstance();
calendar.set(MainActivity.year, MainActivity.month, 1);
int startDayOfWeek=calendar.get(Calendar.DAY_OF_WEEK);
List<Integer> dates=new ArrayList<Integer>();
for (int i=0; i<startDayOfWeek-1; i++) {
dates.add(daysInPrevMonth-i);
}
for (int i=0; i<daysInCurrentMonth; i++) {
dates.add(i+1);
}
ArrayAdapter<Integer> adapter=new ArrayAdapter<Integer>(getActivity(), R.layout.grid_view_cell_layout, R.id.textViewGridCell, dates);
events.setAdapter(adapter);
}
private View initializeCalendarScreen(LayoutInflater inflater) {
View layout=inflater.inflate(R.layout.calendar_layout, null);
events=(GridView)layout.findViewById(R.id.gridViewCalendar);
updateGridView();
return layout;
}
}
它工作得很好(我将它用于 FragmentPagerAdapter)。我使用 Activity 中的 updateGridView() 方法来更新 GridView 中的值。但是如果我这样做,我会得到 NullPointerException,因为 ArrayAdapter 的 getActivity() 返回 null。请告诉我,如何从 Activity 更新 Fragment UI?谢谢