问题描述
在配置发生了变化,我的ListView复选框状态迷路了,我明白为什么。我尝试实施
When a config change happens, my ListView Checkbox states get lost, which I understand why.I try to implement
public void onSaveInstanceState(final Bundle outState)
在我的片段之一。所以,我只是想知道什么是存储我的SparseBooleanArray以最简单的方式的 outState 的。
in one of my Fragments. So I'm just wondering what's the easiest way to store my SparseBooleanArray in the outState.
此外,我有点糊涂了,因为ListView中有方法:
Also, I'm a bit confused, as ListView has the method:
getListView().getCheckedItemPositions();
这是什么好?
What's this good for?
推荐答案
在我的情况下,我最终通过实施围绕SparseBooleanArray一个Parcelable包装,像这样做:
In my case, I ended up doing it by implementing a Parcelable wrapper around the SparseBooleanArray, like this:
import android.os.Parcel;
import android.os.Parcelable;
import android.util.SparseBooleanArray;
public class SparseBooleanArrayParcelable extends SparseBooleanArray implements Parcelable {
public static Parcelable.Creator<SparseBooleanArrayParcelable> CREATOR = new Parcelable.Creator<SparseBooleanArrayParcelable>() {
@Override
public SparseBooleanArrayParcelable createFromParcel(Parcel source) {
SparseBooleanArrayParcelable read = new SparseBooleanArrayParcelable();
int size = source.readInt();
int[] keys = new int[size];
boolean[] values = new boolean[size];
source.readIntArray(keys);
source.readBooleanArray(values);
for (int i = 0; i < size; i++) {
read.put(keys[i], values[i]);
}
return read;
}
@Override
public SparseBooleanArrayParcelable[] newArray(int size) {
return new SparseBooleanArrayParcelable[size];
}
};
public SparseBooleanArrayParcelable() {
}
public SparseBooleanArrayParcelable(SparseBooleanArray sparseBooleanArray) {
for (int i = 0; i < sparseBooleanArray.size(); i++) {
this.put(sparseBooleanArray.keyAt(i), sparseBooleanArray.valueAt(i));
}
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
int[] keys = new int[size()];
boolean[] values = new boolean[size()];
for (int i = 0; i < size(); i++) {
keys[i] = keyAt(i);
values[i] = valueAt(i);
}
dest.writeInt(size());
dest.writeIntArray(keys);
dest.writeBooleanArray(values);
}
}
这允许你保存和只是在做加载SparseBooleanArray:
This allows you to save and load your SparseBooleanArray by just doing:
Bundle bundle; //For your activity/fragment state, to include in an intent, ...
SparseBooleanArray sbarray; //Probably from your listview.getCheckedItemPositions()
//Write it
bundle.putParcelable("myBooleanArray", new SparseBooleanArrayParcelable(sbarray));
//Read it back
sbarray = (SparseBooleanArray) bundle.getParcelable("myBooleanArray");
只是我的0.02€
Just my .02€
这篇关于最好的方式来存储SparseBooleanArray的包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!