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

Android 在多选列表视图中保存复选框的选中状态,android,listview,android-checkbox,Android,Listview,Android Checkbox,我是这个多选列表视图的新手。我想在listview中保存复选框的选中状态,这样,如果用户关闭应用程序,然后再次打开,选中的复选框仍然保持选中状态。有没有办法做到这一点。我搜索了它,发现它可以使用SharedReference来完成,但我没有得到关于如何使用它的更多信息。谢谢 public class MainActivity extends AppCompatActivity { ListView myList; Button getChoice; String[]

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

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

            }
        });



    }
}
public类MainActivity扩展了AppCompatActivity{
列表视图myList;
按钮选择;
字符串[]listContent={
“一月”,
“二月”,
“三月”,
“四月”,
“五月”,
“六月”,
“七月”,
“八月”,
“9月”,
“十月”,
“11月”,
“12月”
};
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myList=(ListView)findViewById(R.id.list);
getChoice=(按钮)findViewById(R.id.getChoice);
ArrayAdapter=新的ArrayAdapter(这个,android.R.layout.simple\u list\u item\u多选,listContent);
myList.setChoiceMode(ListView.CHOICE\u MODE\u MULTIPLE);
myList.setAdapter(适配器);
getChoice.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
所选字符串=”;
int cntChoice=myList.getCount();
SparseBooleanArray SparseBooleanArray=myList.getCheckedItemPositions();
for(int i=0;i
在列表项上按如下方式设置复选框

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调用中,只需根据模型重置状态。 有关详细信息,您可以向-


希望它能帮助您:)

首先,您需要为所选值维护布尔数组,然后您可以将其存储在SharedReference中,您还需要自定义适配器,请检查

活动

@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);
}
@覆盖
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[]listArray=新字符串[]{//添加字符串值};
SharedReferences SharedReferences=GetSharedReferences(“状态”,模式\私有);
Boolean[]checkedStatus=新的Boolean[listary.length];
对于(int index=0;index
这样试试

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();
}
公共类CustomAdapter扩展ArrayAdapter实现CompoundButton.OnCheckedChangeListener{
字符串[]值;
布尔[]检查状态;
公共CustomAdapter(上下文上下文、int资源、字符串[]值、布尔[]checkedStatus){
超级(上下文、资源、价值观);
这个值=值;
this.checkedStatus=checkedStatus;
}
@凌驾
public int getCount(){
返回值.length;
}
@凌驾
公共字符串getItem(int位置){
返回值[位置];
}
@凌驾
公共长getItemId(int位置){
返回0;
}
@凌驾
公共视图getView(int位置、视图转换视图、视图组父视图){
视图=转换视图;
如果(视图==null){
LayoutInflater充气器=(LayoutInflater)getContext().getSystemService(Context.LAYOUT\u充气器\u SERVICE);
视图=充气机。充气(R.layout.row_布局,空);
}
TextView TextView=(TextView)view.findViewById(R.id.title);
setText(值[位置]);
复选框=(复选框)view.findViewById(R.id.chk);
box.setTag(位置);
setOnCheckedChangeListener(这个);
box.setChecked(checkedStatus[位置]);
返回视图;
}
@凌驾
检查更改后的公共无效(复合按钮视图,布尔值已检查){
整数索引=(整数)按钮视图.getTag();
已检查状态[索引]=已检查;
字符串键=index.toString();
SharedReferences SharedReferences=getContext().GetSharedReferences(“状态”,Context.MODE\u PRIVATE);
SharedReferences.Editor=SharedReferences.edit();
编辑器.putBoolean(键,已选中);
editor.apply();
}

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

因此,您的
onCreate
onDestroy
方法如下所示:

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;
}
SharedReferences SharedReferences=GetSharedReferences(“MySharedPrefs”,MODE_PRIVATE);
@凌驾
创建时受保护的void(最终捆绑包savedInstanceState){
...
Set checkedItemsSource=SharedReferences.getStringSet(“checked_items”,new HashSet());
SparseBooleanArray checkedItems=转换为checkedItems(checkedItemsSource);
对于(int i=0;i