在多 select 列表视图中保存复选框的选中状态

save checked state of checkbox in multi select listview

我是这个多select 列表视图的新手。我想在列表视图中保存复选框的选中状态,这样如果用户关闭应用程序然后再次打开,selected 复选框仍然保持 selected。有什么办法可以做到这一点。我搜索了它,发现它可以使用 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();

            }
        });



    }
}

在列表项上,像这样勾选你的复选框

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

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

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

那就这样吧

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

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

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

寻求帮助

希望对您有所帮助:)

首先你需要为选定的值维护布尔数组,然后你可以将它存储在 sharedpreference 中,你还需要自定义适配器,还要检查 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);
}

试试这个方法

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

您可以保存状态,例如,在 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;
}