用GridView 創建的日歷應用,每次轉換人物肖像到風景就不能保存當前狀態,比如,把十一月從人物肖像視圖轉換到風景視圖,回來就會變成了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);
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();
}
}
/**
*/
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);
}
mCalendar.set(year, month - 1 , 1);
此外,建議直接實用month而不是calendar作為保存和恢復的對象,更簡單。