2015-03-08 88 views
-1

我有一個自定義適配器兩行(textview)和一個複選框的列表視圖。 我想關閉應用程序時保存複選框的狀態,但我不知道如何,我嘗試了很多東西,但沒有任何東西!複選框+ customAdapter + listview + sharedpreferences

我可以用android.R.layout.simple_list_item_multiple_choice來做到這一點,但沒有用我的適配器。

  • 的onCreate

    private SimpleAdapter notes; 
    ArrayList<HashMap<String, String>> arraylist_hashmap = new ArrayList<HashMap<String, String>>(); 
    
    if (lenguage.equals("Deutsch")) { 
          HashMap<String, String> item; 
          for (int i = 0; i < StatesAndCapitalsAleman.length; i++) { 
           item = new HashMap<String, String>(); 
           item.put("line1", StatesAndCapitalsAleman[i][0]); 
           item.put("line2", StatesAndCapitalsAleman[i][1]); 
           arraylist_hashmap.add(item); 
          } 
    
    notes = new SimpleAdapter(this, arraylist_hashmap, R.layout.main_item_two_line_row, 
          new String[] { "line1", "line2" }, 
          new int[] { R.id.text1, R.id.text2 }); 
    
        getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); 
        setListAdapter(notes); 
    
  • 保存狀態

    @Override 
        public void onBackPressed() { 
         // TODO Auto-generated method stub 
         SaveSelections(); 
         super.onBackPressed(); 
        } 
    
    private void SaveSelections() { 
        // save the selections in the shared preference in private mode for the 
        // user 
        SharedPreferences.Editor prefEditor = sharedpreferences.edit(); 
        String savedItems = getSavedItems(); 
        prefEditor.putString(MyPREFERENCES.toString(), savedItems); 
        prefEditor.commit(); 
    } 
    
    private String getSavedItems() { 
         String savedItems = ""; 
         int count = this.listView_ale.getAdapter().getCount(); 
         for (int i = 0; i < count; i++) { 
          if (this.listView_ale.isItemChecked(i)) { 
           if (savedItems.length() > 0) { 
            savedItems += "," + this.listView_ale.getItemAtPosition(i); 
           } else { 
            savedItems += this.listView_ale.getItemAtPosition(i); 
           } 
          } 
         } 
         return savedItems; 
        } 
    

回答

0

您需要創建一個與自己的模型創建自定義適配器。 按照您的要求創建具有選定布爾型字段和其他字段的模型。然後爲您的列表創建一個自定義適配器。然後您可以將複選框的檢查狀態中的模型對象修改爲true/false,後者可以根據您的要求保存狀態。