dimanche 18 août 2019

How do you permanently store the state of check mark in the checkbox within the app?

Now I know this question has been answered before, but in my case it is a bit different. I built the check boxes within the listview as shown and the onClick call can only be specific to one of these boxes as far as I can tell.

The sharedpreference would only manage to save the biggest one in terms of the index.

          for(int i = 0; i < l.size(); i++) {
            int check = preferences.getInt(Integer.toString(i), -1);

            checkBox = new CheckBox(getContext());

            checkBox.setText(l.get(i));
            checkBox.setId(i);
            listView.addFooterView(checkBox);
            if(i == check) {
                checkBox.post(new Runnable() {
                    @Override
                    public void run() {
                        checkBox.setChecked(true);
                    }
                });
            }
            checkBox.setOnCheckedChangeListener(new 
                CompoundButton.OnCheckedChangeListener() {
                @Override
  public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
           if (checkBox.isChecked()) {

           preferences.edit().putInt(Integer.toString(checkBox.getId()), 
           checkBox.getId()).apply();
           System.out.println("ID:" + checkBox.getId());
                    }
                }
            });
        }




Aucun commentaire:

Enregistrer un commentaire