save checked state of checkbox in multi select listview

白昼怎懂夜的黑 提交于 2019-12-12 19:21:25

问题


I'm new to this multi-select listview. I want to save the checked state of the checkbox in the listview so that if user closes the app and then opens again, the selected checkbox still remain selected. Is there any way to do this. I searched for it and found that it can be done using SharedPreference but I didn't get more information on how to use it. Thanks

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();

            }
        });



    }
}

回答1:


You can save state, for example, in SharedPreferences.

So your onCreate and onDestroy methods will be look like:

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;
}



回答2:


on list item set your checkbox checked like this

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());
                }
            }
        });

Store the selected items in a sharedprefrence and then on button hit make a comparision between all present items in list and item stored in shared prefrence like this

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

then just do this

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

Now pass this to adapter constructor this saves the check box state and also retrives it




回答3:


For that you need to maintain the status in your model. And on every onBindView call just reset the status as per model. For details you can take help from -

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

Hope it will help you :)




回答4:


First of all you need to maintain boolean array for selected values and then you can store it in sharedpreference and you also need custom adapter for that,also check Multiple Checkbox values in listview storing & retrieving using sharedpreferences

Activity

@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);
}

try this way

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();
}


来源:https://stackoverflow.com/questions/38630060/save-checked-state-of-checkbox-in-multi-select-listview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!