如何保存/恢复附加到ListView
的{{1}}状态?例如:
我有一个Android CursorAdapter
,其中包含3个Activity
:国家,地区,城市。
它们附加到3 ListView
:SimpleCursorApdater
,CountryAdapter
,RegionAdapter
。
CityAdapter
RegionAdapter
伪代码:
CityAdapter
调用void countryList_onItemSelected() {
regionsAdapter.getFilter().filter(countryId);
}
void regionList_onItemSelected() {
cityAdapter.getFilter().filter(regionId);
}
Cursor regionAdapter_FilterQueryProvider_runQuery(countryId) {
Cursor cur = dbHelper.getReadableDatabase().
query("Select * from Region where countryId = "+countryId);
return cur;
}
Cursor cityAdapter_FilterQueryProvider_runQuery(regionId) {
Cursor cur = dbHelper.getReadableDatabase().
query("select * from City where regionId = "+regionId);
return cur;
}
时,onRestoreInstanceState()
为空,因为尚未终止2 cityListView
个方法。所以我不能直截了当:
runQuery()
问题:
如何使用void onRestoreInstanceState(Bundle state) {
...
savedCitySelection = state.getInt("citySelectedItemPosition")
cityListView.setSelection(savedCitySelection); // <= NOOO! the cityListView is empty
}
和onSaveInstanceState()
答案 0 :(得分:1)
我建议使用Loader
。
然后当加载完成并且您将光标交换进来时,您可以在smoothScrollToPosition(int position)
上拨打ListView
*。
CommonsWare在这里有一个很好的基于支持库的CursorLoader:
https://github.com/commonsguy/cwac-loaderex
* (注意:smoothScrollToPosition需要Android 2.2)