【问题标题】:save checked state of checkbox in multi select listview在多选列表视图中保存复选框的选中状态
【发布时间】:2016-07-28 07:43:22
【问题描述】:

我是这个多选列表视图的新手。我想在列表视图中保存复选框的选中状态,以便如果用户关闭应用程序然后再次打开,选中的复选框仍保持选中状态。有没有办法做到这一点。我搜索了它,发现它可以使用 SharedPreference 来完成,但我没有获得有关如何使用它的更多信息。谢谢

public class MainActivity extends AppCompatActivity {

    ListView myList;
    Button getChoice;

    String[] listContent = {

            "January",
            "February",
            "March",
            "April",
            "May",
            "June",
            "July",
            "August",
            "September",
            "October",
            "November",
            "December"

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        myList = (ListView)findViewById(R.id.list);
        getChoice = (Button)findViewById(R.id.getchoice);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, listContent);
        myList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

        myList.setAdapter(adapter);

        getChoice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String selected = "";
                int cntChoice = myList.getCount();

                SparseBooleanArray sparseBooleanArray = myList.getCheckedItemPositions();
                for(int i = 0; i < cntChoice; i++){
                    if(sparseBooleanArray.get(i)) {
                        selected += myList.getItemAtPosition(i).toString() + "\n";

                    }

                }

                Toast.makeText(MainActivity.this, selected, Toast.LENGTH_LONG).show();

            }
        });



    }
}

【问题讨论】:

    标签: android listview android-checkbox


    【解决方案1】:

    您可以保存状态,例如,在 SharedPreferences 中。

    所以您的 onCreateonDestroy 方法将如下所示:

    SharedPreferences sharedPreferences = getSharedPreferences("MySharedPrefs", MODE_PRIVATE);
    
    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        ...
        Set<String> checkedItemsSource = sharedPreferences.getStringSet("checked_items", new HashSet<String>());
        SparseBooleanArray checkedItems = convertToCheckedItems(checkedItemsSource);
        for (int i = 0; i < checkedItems.size(); i++) {
            int checkedPosition = checkedItems.keyAt(i);
            listView.setItemChecked(checkedPosition, true);
        }
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        SparseBooleanArray checkedItems = listView.getCheckedItemPositions();
        Set<String> stringSet = convertToStringSet(checkedItems);
        sharedPreferences.edit()
                .putStringSet("checked_items", stringSet)
                .apply();
    }
    
    private SparseBooleanArray convertToCheckedItems(Set<String> checkedItems) {
        SparseBooleanArray array = new SparseBooleanArray();
        for(String itemPositionStr : checkedItems) {
            int position = Integer.parseInt(itemPositionStr);
            array.put(position, true);
        }
    
        return array;
    }
    
    private Set<String> convertToStringSet(SparseBooleanArray checkedItems) {
        Set<String> result = new HashSet<>();
        for (int i = 0; i < checkedItems.size(); i++) {
            result.add(String.valueOf(checkedItems.keyAt(i)));
        }
    
        return result;
    }
    

    【讨论】:

    • 当我在我的应用程序中运行您的代码时,应用程序在 SharedPreferences sharedPreferences = getSharedPreference@Michael 行出现 NPE 崩溃
    • 无论如何解决了。顺便说一句,你的代码是最好的人。 @迈克尔。
    • 另外,有什么办法可以删除这个共享偏好?
    【解决方案2】:

    在列表项上设置您的复选框,如下所示

    listView.setOnItemClickListener(new OnItemClickListener()
            {
                public void onItemClick(AdapterView<?> parent, View view, int position, long id)
                {
                    AppListOfAllApps hideSelectedApps = (AppListOfAllApps) parent.getItemAtPosition(position);
                    if (view != null)
                    {
                        CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBox1);
                        hideSelectedApps = (AppListOfAllApps) checkBox.getTag();
                        hideSelectedApps.setSelected(!checkBox.isChecked());
                        checkBox.setChecked(!checkBox.isChecked());
                    }
                }
            });
    

    将所选项目存储在 sharedprefrence 中,然后点击按钮,对列表中的所有当前项目和存储在共享 prefrence 中的项目进行比较,如下所示

    boolean chkbox = false;
            String selecteditem = SharedPreferences.getSharedPref(getApplicationContext()).selecteditem();
    

    那就这样做吧

    if (allitems.contains(selecteditem ))
                    {
                        chkbox = true;
                    }
                    else
                    {
                        chkbox = false;
                    }
    

    现在将它传递给适配器构造函数 这将保存复选框状态并检索它

    【讨论】:

    • 这里的AppListOfAllApps 是什么?以及如何在 SharedPreference 中保存选定的项目?
    • 对不起,我添加了我的代码,我已经实现了你想要做的......appslistofallapps 是你的适配器中的 allitems....... 用键值对兄弟保存所选项目跨度>
    【解决方案3】:

    为此,您需要维护模型中的状态。在每个 onBindView 调用中,只需根据模型重置状态。 有关详细信息,您可以向 -

    寻求帮助

    https://stackoverflow.com/a/38182528/1741586

    希望对你有帮助:)

    【讨论】:

    • 我正在使用列表视图。那么如何在这里使用带有listview的模型类呢? @Neo
    • 它很简单,只需使用所有数据制作模型,您需要一行。在 getView 中,只需根据模型更新您的复选框。以及模型中复选框变化的状态变化。
    • 试试吧!如果仍然无法解决问题,请告诉我,我很乐意提供帮助:)
    【解决方案4】:

    首先你需要为选定的值维护布尔数组,然后你可以将它存储在 sharedpreference 中,你还需要自定义适配器,也请检查Multiple Checkbox values in listview storing & retrieving using sharedpreferences

    活动

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
    
    
        String[] listArray = new String[] { //Add String values };
        SharedPreferences sharedPreferences = getSharedPreferences("status", MODE_PRIVATE);
    
        Boolean[] checkedStatus = new Boolean[listArray.length];
        for ( int index = 0; index < checkedStatus.length; index++)
            checkedStatus[index] = sharedPreferences.getBoolean(Integer.toString(index), false);
    
        ListView listView = (ListView) findViewById(R.id.listview);
        CustomAdapter adapter = new CustomAdapter(this, R.layout.row_layout, listArray, checkedStatus);
        listView.setAdapter(adapter);
    }
    

    试试这个方法

    public class CustomAdapter extends ArrayAdapter<String> implements CompoundButton.OnCheckedChangeListener{
    
    String[] values;
    Boolean[] checkedStatus;
    
    public CustomAdapter(Context context, int resource, String[] values, Boolean[] checkedStatus) {
        super(context, resource, values);
    
        this.values = values;
        this.checkedStatus = checkedStatus;
    }
    
    @Override
    public int getCount() {
        return values.length;
    }
    
    @Override
    public String getItem(int position) {
        return values[position];
    }
    
    @Override
    public long getItemId(int position) {
        return 0;
    }
    
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        if(view == null){
            LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.row_layout, null);
        }
    
        TextView textView = (TextView) view.findViewById(R.id.title);
        textView.setText(values[position]);
    
        CheckBox box = (CheckBox) view.findViewById(R.id.chk);
        box.setTag(position);
        box.setOnCheckedChangeListener(this);
        box.setChecked(checkedStatus[position]);
    
        return view;
    }
    
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        Integer index = (Integer) buttonView.getTag();
        checkedStatus[index] = isChecked;
        String key = index.toString();
    
        SharedPreferences sharedPreferences=getContext().getSharedPreferences("status", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor=sharedPreferences.edit();
        editor.putBoolean(key,isChecked);
        editor.apply();
    }
    

    【讨论】:

    • 我尝试了你的方式,但它在 Activity 中要求 boolean[]。有什么替代方案吗? @Aditya Vyas
    • 然后在活动中创建布尔值
    猜你喜欢
    • 1970-01-01
    • 2016-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-31
    • 2013-06-14
    相关资源
    最近更新 更多