我正在尝试恢复复选框列表的“已选中”状态,但由于某种原因这些框从未被选中。
我确信我忽略了一些小事情。
如有任何建议,我们将不胜感激。
来源:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_notification_settings_list_new_message);
pref = getApplicationContext().getSharedPreferences("PREFS", 0);
final int selection = pref.getInt("ChatRepeatPosition", 0);
ButterKnife.bind(this);
getSupportActionBar().setTitle("Repeat Notification In");
list = (ListView) findViewById(R.id.simpleListView);
dataAdapter = new ArrayAdapter<String>(this, R.layout.repeat,
R.id.repeat_tv, text);
list.setAdapter(dataAdapter);
list.setChoiceMode(ListView.CHOICE_MODE_NONE);
if (list != null && selection != 0) {
for (int i = 0; i < list.getCount(); i++) {
CheckBox cb = new CheckBox(this);
cb.setId(i);
if (i == selection) {
cb.setChecked(true);
} else {
CheckBox cbb = new CheckBox(this);
cbb.setChecked(false);
}
}
}
完整来源:
编辑:
下面显示的第一个“答案”不是我想要实现的目标。我完全理解如何恢复单个复选框的状态。我在迭代复选框列表以恢复所有复选框的状态时遇到问题(我能够迭代 list.setOnItemClickListener 中的列表,因为我可以获得 View - 但我不确定如何迭代oncreate 中的列表)
最佳答案
问题是您正在创建新的 CheckBox
对象,但没有对它们执行任何操作:
for (int i = 0; i < list.getCount(); i++) {
CheckBox cb = new CheckBox(this);
cb.setId(i);
if (i == selection) {
cb.setChecked(true);
} else {
CheckBox cbb = new CheckBox(this);
cbb.setChecked(false);
}
}
这会循环列表的大小,初始化 CheckBox
,设置这些 CheckBox
的选中状态,然后......好吧,就是这样。它们与 ListView
没有任何关联,那么它的状态如何更新?
您想要做的是使用 setItemChecked方法,类似这样:
final int selection = pref.getInt("ChatRepeatPosition", 0);
list = (ListView) findViewById(R.id.simpleListView);
list.setItemChecked(selection, true);
并且您可以删除实际上不执行任何操作的 for 循环。
如果您想读取多个已保存的选择,则需要从数据库或文件中读取,因为首选项仅限于键/值对。但概念是相同的:读取选择列表,迭代列表,设置在 ListView 上选中的项目。
希望有帮助!
关于java - 恢复 ArrayList 中的 CheckBox 状态永远不会将 CheckBox 设置为已选中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48964104/