2011-09-29 20 views
0

我有一个像显示数据的列表视图:如何去喜好

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

回答

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 
+0

; int sort = prefs.getInt(“sort_pref”,-1); // -1会如果没有倾向性 之前设置的结果,如果(排序== 1) \t \t中将sortOrder = “一年”; //同比 \t否则,如果(排序== 2) \t \t中将sortOrder排序=“country”; //按国家排序然后Cursor c = contentResolver.query(CONTENT_URI,null,null,null,sortOrder);它工作得很好..感谢引导我真的很感激。 – SASM

0

看看排序顺序在Activity中使用getSharedPreferences()来获取SharedPreferences的副本。您可以在onClose()中设置值,然后在您的应用在onCreate重新启动时将其重新选择备份onCreate SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); onCreate()