在screenrotation上,未选中的项目被取消选中,我想保存其状态。 我在recyclerView中拥有所有这些表格,这些都可以在单击时选择。这是onListItemClick中的代码
private void onListItemClick(View view, int position) {
Cursor cursor = instanceAdapter.getCursor();
cursor.moveToPosition(position);
CheckBox checkBox = view.findViewById(R.id.checkbox);
checkBox.setChecked(!checkBox.isChecked());
long id = cursor.getLong(cursor.getColumnIndex(InstanceProviderAPI.InstanceColumns._ID));
if (selectedInstances.contains(id)) {
selectedInstances.remove(id);
} else {
selectedInstances.add(id);
}
Bundle bundle=new Bundle();
sendButton.setEnabled(selectedInstances.size() > 0);
toggleButtonLabel();
}
其中selectedInstances是LinkedHashSet
private LinkedHashSet<Long> selectedInstances;
这是GIF
答案 0 :(得分:1)
除非您可以将其存储在数据库中或“持久”的任何内容中,否则您可以仅保留一个布尔值列表/数组,其条目数与ListView一样多。选中第二个复选框时,设置array [1] = true。
然后,在适配器中,您只需检查当前项目列表位置的状态即可。
一个例子
boolean[] checkedState = new boolean[list.count];
private void onListItemClick(View view, int position) {
//...
checkedState[position] = //checked state
}
//adapter
public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder holder, int position) {
//...
checkBox.isChecked = checkedState[position]
}
答案 1 :(得分:0)
ViewModel存储与应用程序旋转时不会破坏的与UI相关的数据。
答案 2 :(得分:0)
关于保持UI状态,可以使用活动对象的onSaveInstanceState()和onRestoreInstanceState方法将数据保存在Bundle类型参数中,如下所示:
protected void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
String setting;
state.putString("KeyName", setting);
}
protected void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
String setting;
setting = state.getString("KeyName");
}
根据Android开发者文档的规定,保留数据的最正确方法是,当应用程序完成后又重新启动时,该应用程序可以从本地存储中检索该数据。
根据数据复杂性,它可以是 SharedPreferences 或房间数据库。就像数据是设置一样,所以我相信您将要在完成应用程序后存储一个,而在再次启动应用程序时检索一个。
参考: