2011-09-29 68 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()