1

我有一个 2D 枚举数组,我想在我的两个活动之间传递。

目前,我将 2D Enum 数组转换为 2D int 数组,将其传递给 Bundle,然后将其转换为 1D Object 数组,然后转换为 2D int 数组,最后返回到我的 2D Enum 数组。

有一个更好的方法吗?

在检查了 Android 之后,我通过单个枚举没有问题:如何将枚举放入捆绑包中?

我尝试直接传递和检索 2D Enum 数组,但是当我尝试检索它时出现 RuntimeException。

这是我的代码:

将二维数组传递给 Bundle:

    // Send the correct answer for shape arrangement
    Intent intent = new Intent(getApplicationContext(), RecallScreen.class);

    Bundle bundle = new Bundle();

    // Convert mCorrectShapesArrangement (Shapes[][]) to an int[][].
    int[][] correctShapesArrangementAsInts = new int[mCorrectShapesArrangement.length][mCorrectShapesArrangement[0].length];
    for (int i = 0; i < mCorrectShapesArrangement.length; ++i)
        for (int j = 0; j < mCorrectShapesArrangement[0].length; ++j)
            correctShapesArrangementAsInts[i][j] = mCorrectShapesArrangement[i][j].ordinal();

    // Pass int[] and int[][] to bundle.
    bundle.putSerializable("correctArrangement", correctShapesArrangementAsInts);

    intent.putExtras(bundle);

    startActivityForResult(intent, RECALL_SCREEN_RESULT_CODE);

从 Bundle 中检索:

    Bundle bundle = getIntent().getExtras();

    // Get the int[][] that stores mCorrectShapesArrangement (Shapes[][]).      
    Object[] tempArr = (Object[]) bundle.getSerializable("correctArrangement");
    int[][] correctShapesArrangementAsInts = new int[tempArr.length][tempArr.length];
    for (int i = 0; i < tempArr.length; ++i)
    {
        int[] row = (int[]) tempArr[i];
        for (int j = 0; j < row.length; ++j)
            correctShapesArrangementAsInts[i][j] = row[j];
    }

    // Convert both back to Shapes[][].
    mCorrectShapesArrangement = new Shapes[correctShapesArrangementAsInts.length][correctShapesArrangementAsInts[0].length];
    for (int i = 0; i < correctShapesArrangementAsInts.length; ++i)
        for (int j = 0; j < correctShapesArrangementAsInts[0].length; ++j)
            mCorrectShapesArrangement[i][j] = Shapes.values()[correctShapesArrangementAsInts[i][j]];

提前致谢!

4

1 回答 1

0

创建一个自定义类,其中包含在 Enum(getter/setter) 上实现 Parcelable 的 2D 数组然后您可以通过意图传递该自定义类的对象。

class customclass implements Parcelable { 
   public enum Foo { BAR, BAZ }

   public Foo fooValue;

   public void writeToParcel(Parcel dest, int flags) {
      dest.writeString(fooValue == null ? null : fooValue.name());
   }

   public static final Creator<customclass> CREATOR = new Creator<customclass>() {
     public customclass createFromParcel(Parcel source) {        
       customclass e = new customclass();
       String s = source.readString(); 
       if (s != null) e.fooValue = Foo.valueOf(s);
       return e;
     }
   }
 }
于 2012-06-06T04:45:36.037 回答