gpt4 book ai didi

android - 从纵向切换到横向时保存 View 状态

转载 作者:行者123 更新时间:2023-11-29 18:05:16 25 4
gpt4 key购买 nike

我使用 GridView 创建了一个简单的日历,每当我从纵向 View 切换到横向(或返回)时,它都不会保留状态。例如,我在纵向 View 中更改为一月,而在横向 View 中又回到了十二月。我试图解决这个问题并将这段代码添加到我的 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);
}

最佳答案

在设置 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);

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

关于android - 从纵向切换到横向时保存 View 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13713416/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com