我创建了一个简单的日历GridView
,每当我从纵向视图切换到横向(或返回)时,它都不会保留状态。例如,我在纵向视图中更改为 1 月,而在横向视图中更改为 12 月。我试图解决这个问题并将这段代码添加到我的OnCreate()
:
if(savedInstanceState != null && savedInstanceState.containsKey(CALENDAR)){
mCalendar = (Calendar) savedInstanceState.getSerializable(CALENDAR);
}else{
mCalendar = Calendar.getInstance();
}
并将此方法添加到类中:
@Override
public void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
//Save the calendar instance in case the user changed it
outState.putSerializable(CALENDAR, mCalendar);
}
不幸的是,它不想工作,并且在更改手机方向时,几个月仍然会切换到初始状态。有人可以帮帮我吗?
代码:
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendar);
mCalendar = Calendar.getInstance(Locale.getDefault());
month = mCalendar.get(Calendar.MONTH) + 1;
year = mCalendar.get(Calendar.YEAR);
previous = (Button) findViewById(R.id.b_prevMonth);
next = (Button) findViewById(R.id.b_nextMonth);
displayMonth = (TextView) findViewById(R.id.et_displayMonth);
gv_daysOfWeek = (GridView) findViewById(R.id.gv_daysOfWeek);
gv_calendar = (GridView) findViewById(R.id.gv_calendar);
previous.setOnClickListener(this);
next.setOnClickListener(this);
displayMonth.setText(DateFormat.format(monthDisplay, mCalendar.getTime()));
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.weekdays_grid, R.id.grid_item_label, WEEK_DAYS);
gv_daysOfWeek.setAdapter(adapter);
setGridCellAdapter(month, year);
if(savedInstanceState != null && savedInstanceState.containsKey(CALENDAR)){
mCalendar = (Calendar) savedInstanceState.getSerializable(CALENDAR);
}else{
mCalendar = Calendar.getInstance();
}
}
/**
* Method responsible for intialising the adapter
*/
private void setGridCellAdapter(int month, int year) {
cellAdapter = new GridCellAdapter(getApplicationContext(),R.id.day_gridcell, month, year);
mCalendar.set(year, month - 1 , mCalendar.get(Calendar.DAY_OF_MONTH));
displayMonth.setText(DateFormat.format(monthDisplay, mCalendar.getTime()));
cellAdapter.notifyDataSetChanged();
gv_calendar.setAdapter(cellAdapter);
}