1

2 つのアクティビティ間で渡したい Enum の 2D 配列があります。

現在、2D Enum 配列を 2D int 配列に変換して Bundle に渡し、反対側で 1D Object 配列に変換し、次に 2D int 配列に変換し、最後に 2D Enum 配列に戻します。

これを行うより良い方法はありますか?

Android: How to put an Enum in a Bundle? をチェックした後、単一の列挙型を渡すことに問題はありません。

2D Enum 配列を直接渡したり取得したりしようとしましたが、取得しようとすると RuntimeException が発生します。

これが私のコードです:

2D 配列をバンドルに渡す:

    // 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 = 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

Parcelableを実装する Enum(getter/setter) に 2D 配列を含む customclass を作成すると、その customclass のオブジェクトをインテントで渡すことができます。

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 に答える