在我的应用程序中,我有RecyclerView
,用户可以为其中的项目选择不同类型的排序。订购基于Comparator
。
让我们假设用户旋转设备:配置更改后,我想恢复项目的顺序。我想过这样做:
public interface ItemComparator<T> extends Comparator<T>, Serializable { }
public class TestActivity extends AppCompatActivity {
private static final String KEY_COMP = "COMP";
private ItemComparator<MyItem> comparator;
protected void onCreate(@Nullable Bundle savedState) {
// main setup
if(savedState == null) {
comparator = (a, b) -> a.getName().compareTo(b.getName());
} else {
// unsafe cast here - can I get rid of it?
comparator = (ItemComparator<MyItem>) savedState.getSerializable(KEY_COMP);
}
}
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable(KEY_COMP, comparator);
}
}
这是有效代码还是会导致内存泄漏或其他任何问题?
答案 0 :(得分:2)
为此,您可以为每个订单创建一个Sorter
比较器。该类使用字段和方向参数进行排序,这是您保存到包中的值。
public class Sorter implements Comparator<Item> {
public static final int SORT_BY_DATE = 0;
public static final int SORT_BY_DESCRIPTION = 1;
public static final int SORT_BY_AMOUNT = 2;
public static final int SORT_DIR_ASCENDING = 1;
public static final int SORT_DIR_DESCENDING = -1;
private int field;
private int direction;
public Sorter(int field, int direction) {
this.field = field;
this.direction = direction;
}
public int getField() {
return field;
}
public int getDirection() {
return direction;
}
@Override
public int compare(Item i1, Item i2) {
int order = 0;
switch (field) {
case SORT_BY_DATE:
order = Long.compare(i1.date, i2.date);
break;
case SORT_BY_DESCRIPTION:
order = i1.description.compareTo(i2.description)
break;
case SORT_BY_AMOUNT:
order = Integer.compare(i1.amount, i2.amount)
break;
}
return order * direction;
}
}
在onCreate()
:
if (savedState == null) {
// Default parameters
comparator = new Sorter(Sorter.SORT_BY_DATE, Sorter.SORT_DIR_ASCENDING);
} else {
int field = bundle.getInt("comparatorField");
int dir = bundle.getInt("comparatorDir");
comparator = new Sorter(field, dir)
}
在onSaveInstanceState(Bundle savedState)
:
bundle.putInt("comparatorField", comparator.getField());
bundle.putInt("comparatorDir", comparator.getDirection());
将比较器串行化绝对不是要走的路,事实上,你应该avoid using that with Android in general。