从纵向切换到横向时保存视图的状态

时间:2012-12-04 22:53:15

标签: android orientation savestate

我使用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);
 }

2 个答案:

答案 0 :(得分: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()的所有其他代码。

答案 1 :(得分:0)

试试这个:

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

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