1

我创建了一个简单的日历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);
 }
4

2 回答 2

3

在设置 GridView之前您不会读取已保存的状态...更改您的代码以首先读取已保存的状态:

if(savedInstanceState != null && savedInstanceState.containsKey(CALENDAR)){
    mCalendar = (Calendar) savedInstanceState.getSerializable(CALENDAR);
}else{
    mCalendar = Calendar.getInstance(Locale.getDefault());
}
month = mCalendar.get(Calendar.MONTH) + 1;
year = mCalendar.get(Calendar.YEAR);

// Initialize your Buttons and such...

setGridCellAdapter(month, year);

删除任何其他试图设置mCalendar的代码onCreate()

于 2012-12-04T23:32:11.020 回答
0

试试这个:

mCalendar.set(year, month - 1 , 1);

建议:如果你使用月份作为保存和恢复对象而不是日历会更简单。

于 2012-12-05T05:45:25.087 回答