我试图恢复一个复选框列表'缺血'然而,由于某种原因,从未检查过盒子。
我确定我忽略了一些小事。
任何建议都表示赞赏。
@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);
}
}
}
完整来源:
第一个回答&#39;如下所示不是我试图完成的。我完全理解如何恢复单个复选框的状态。我无法遍历我的复选框列表以恢复所有这些复选框的状态(我能够遍历list.setOnItemClickListener中的列表,因为我可以获得视图 - 但我不知道如何迭代oncreate中的列表)
答案 0 :(得分:2)
问题是您正在创建新的<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:scrollbars="vertical"
app:layout_constrainedHeight="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHeight_max="300dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
个对象而不对它们做任何事情:
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);
}
}
s,在CheckBox
s上设置检查状态,然后......好吧,那就是它。它们与CheckBox
无关,那么它的状态如何更新呢?
您要做的是使用setItemChecked方法,如下所示:
ListView
你可以删除字面上什么都不做的for循环。
如果要读取多个已保存的选择,则需要从数据库或文件中读取,因为首选项仅限于键/值对。但概念是相同的:读取选择列表,遍历列表,在列表视图上设置项目。
希望有所帮助!
答案 1 :(得分:1)
试试这个..在创建时添加你的复选框并初始化它。
cb1 = (CheckBox) findViewById(R.id.yourxmlid);
然后添加一个共享的pref来检查复选框的状态
sharedpreferences = PreferenceManager.getDefaultSharedPreferences(this);
editor = sharedpreferences.edit();
boolean checkedFlag1 = sharedpreferences.getBoolean("checkboxstate", false);
cb1.setChecked(checkedFlag1);
然后最后在你的onCheckListener中添加一个共享的pref来检查框
cb1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (cb1.isChecked()) {
editor.putBoolean("checkboxstate", true);
editor.commit();
Log.i("Checkbox ", "Activated");
}else{
editor.putBoolean("checkboxstate", false);
editor.commit();
Log.i("Checkbox: ","Deactivated");
}
}
});