我有一个 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]];
提前致谢!