2 o19830015 o19830015 于 2012.12.05 10:58 提问

人物肖像到风景转换的时候保存视图状态

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

1个回答

cytown
cytown   2012.12.05 11:11
已采纳

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

此外,建议直接实用month而不是calendar作为保存和恢复的对象,更简单。

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!