Android:如何将2D枚举数组传递给Bundle?

时间:2012-06-06 04:41:52

标签: android arrays enums 2d bundle

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

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

有更好的方法吗?

在签出Android: How to put an Enum in a Bundle?

之后,我在传递单个枚举方面没有任何问题

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

这是我的代码:

将2D数组传递给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]];

提前致谢!

1 个答案:

答案 0 :(得分:0)

创建一个自定义类,其中包含实现Parcelable的Enum(getter / setter)上的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;
     }
   }
 }