我有一个列表视图,显示如下数据:
2010新加坡 2009年印度 2011年瑞典 2010年德国
现在,当我点击菜单按钮时,我有两个项目,让我可以根据年份或国家/地区对此列表进行排序。分拣工作正常。
我现在要做的是,当我点击两个选项中的任何一个时,它应该相应地对列表进行排序,现在还应该保存它在首选项中的排序方式。因此,下次打开应用程序时,应该按照首选项中存储的内容进行排序。我应该遵循什么方法。我的意思是我如何存储我在偏好中上次排序的值。我尝试了一些教程,但没有完全理解
实际上我只想在首选项中保存最后的排序顺序。下次用户启动应用程序时,国家/地区列表的排序方式应与上次用户关闭应用时的排序方式相同。
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(Menu.NONE, SORT_BY_YEAR, Menu.NONE, "Sort by Year")
.setAlphabeticShortcut('y');
menu.add(Menu.NONE, SORT_BY_COUNTRY, Menu.NONE, "Sort by Country")
.setAlphabeticShortcut('c');
return(super.onCreateOptionsMenu(menu));
}
/* (non-Javadoc)
* @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
String[] from = new String[] { "year", "country" };
int[] to = new int[] { R.id.year, R.id.country };
switch (item.getItemId()) {
case SORT_BY_YEAR:
Cursor cYear = getContentResolver().query(CONTENT_URI, null, null, null, "year");
SimpleCursorAdapter scaYear = new SimpleCursorAdapter(this, R.layout.country_row,cYear, from, to);
setListAdapter(scaYear);
sortOrder = "year";
return(true);
case SORT_BY_COUNTRY:
Cursor cCountry = getContentResolver().query(CONTENT_URI, null, null, null, "country");
SimpleCursorAdapter scaCountry = new SimpleCursorAdapter(this, R.layout.country_row,cCountry, from, to);
setListAdapter(scaCountry);
sortOrder = "country";
return(true);
}
return(super.onOptionsItemSelected(item));
}
答案 0 :(得分:2)
您是否考虑过使用SharedPreferences存储首选排序顺序?
当用户选择排序顺序时,您将其存储在共享首选项中,例如
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
prefs.edit().putInt("sort_pref", 1).commit(); // 1 = sort on year
下次打开应用时,您可以阅读偏好值
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
int sort = prefs.getInt("sort_pref", -1); // -1 will be the result if no preference was set before
if(sort == 1)
///sort on year
else if (sort == 2)
///sort on country
答案 1 :(得分:0)
查看Activity中的getSharedPreferences()以获取SharedPreferences的副本。您可以在onClose()中设置值,然后在应用程序重新启动onCreate()时再次将其重新选回