checkbox + customAdapter + listview + sharedpreferences

时间:2015-03-08 17:41:35

标签: android

我有一个listview,其中包含两行自定义适配器(textview)和一个复选框。 我想在关闭应用程序时保存复选框的状态,但我不知道如何,我尝试了很多东西,但什么都没有!

我可以用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;
        }
    

1 个答案:

答案 0 :(得分:0)

您需要使用自己的模型创建一个自定义适配器。 根据您的要求创建具有选定布尔字段的模型和其他字段。然后为列表创建自定义适配器。然后你可以将复选框的检查状态中的模型对象修改为选中的true / false,然后根据你的要求保存状态。