使用ArrayList <enum>的Android Parcelable实现

时间:2015-10-12 06:01:56

标签: android arraylist enums parcelable

这是我的实施:

public class MuscleFilters extends BaseFilters<Muscle>  {
  ... some just methods
}

public abstract class BaseFilters<T> extends ArrayList<T>  {
  ... some just methods
}

public enum Muscle implements Parcelable {
   @SerializedName("abductors")
   ABDUCTORS(0, "abductors"),
   @SerializedName("abs")
   ABS(1, "abs"),
   ...

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(final Parcel dest, final int flags) {
    dest.writeInt(ordinal());
}

public static final Creator<Muscle> CREATOR = new Creator<Muscle>() {
    @Override
    public Muscle createFromParcel(final Parcel source) {
        return Muscle.values()[source.readInt()];
    }

    @Override
    public Muscle[] newArray(final int size) {
        return new Muscle[size];
    }
};

从特定的Activity(ActivityB)中,我将用户选择的所有过滤器放在标准的ArrayList中:

ArrayList filters = new ArrayList<>();
MuscleFilters musclesFilters = new MuscleFilters();
...
filters.add(musclesFilters);

LevelFilters levelFilters = new LevelFilters();
...
filters.add(levelFilters);

...

然后我发送到上一个Activity(ActivityA)这个结果:

Intent args = getIntent();
args.putParcelableArrayListExtra(BUNDLE_KEY_FILTERS, filters);
setResult(RESULT_OK, args);

在ActivityA中,我检索结果:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {
        switch (requestCode) {
            case REQUEST_CODE_FILTER_EXERCISES:
                ArrayList filters = data.getParcelableArrayListExtra(FiltersActivity.BUNDLE_KEY_FILTERS);
                ...
                break;
        }
    }
}

这个getParcelableArrayListExtra()几乎正常工作,也就是说:

  • 过滤器实际上是一个正确的 ArrayList
  • 但其中的所有数据都是 ArrayList 而不是 BaseFilter

我不能那样做,因为有一个崩溃(CastList类型不可能将ArrayList转换为BaseFilter)

for (BaseFilters filter : filters) {
       ...            
}

你能帮帮我们吗?

非常感谢!

0 个答案:

没有答案