Android setImageResource()上的OutOfMemory异常

Android setImageResource()上的OutOfMemory异常,android,android-layout,Android,Android Layout,我有一个应用程序,在活动中显示4个imageview。我将所有可能的图像存储在res/drawable文件夹中。这些图像都是.png,范围从5KB到22KB不等,都是300x300像素。通过如下方法将图像设置为: private void displayChoices() { iv1.setImageResource(mArrayList.get(0) .getResourceId(this)); iv2.setImageResource(mArrayLi

我有一个应用程序,在活动中显示4个
imageview
。我将所有可能的图像存储在res/drawable文件夹中。这些图像都是.png,范围从5KB到22KB不等,都是300x300像素。通过如下方法将图像设置为:

private void displayChoices() {
    iv1.setImageResource(mArrayList.get(0)
            .getResourceId(this));
    iv2.setImageResource(mArrayList.get(1)
            .getResourceId(this)); // <--Usually fails on second image.
    iv3.setImageResource(mArrayList.get(2)
            .getResourceId(this));
    iv4.setImageResource(mArrayList.get(3)
            .getResourceId(this));
}
图像以2x2网格显示,均匀分布在屏幕上

 <LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:baselineAligned="false"
    android:orientation="horizontal" > 
    <FrameLayout
        android:id="@+id/choice_1_frame"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:padding="5dip" >

        <ImageView
            android:id="@+id/choice_1_image"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_gravity="center"
            android:adjustViewBounds="true"
            android:src="@drawable/test_image300x300" />
    </FrameLayout>
    //repeat frame layout
 </LinearLayout>
 //Repeat LinearLayout

//重复帧布局
//重复线性布局

我试图在每次调用该方法时清除对旧图像的引用,但在第一次调用时失败,所以我现在迷路了。关于如何阻止OutOfMemory异常发生的任何想法。

我解决这个问题的方法是只记住图像的资源id。我写了一个记忆游戏,有多张牌和大量的图片。仅在绘制时使用资源id。为此,我建议使用曲面视图并使用onDraw()显示图像

onDraw()中的示例:

mBoard[x][y]包含资源id,是游戏板

bmp = BitmapFactory.decodeResource(mRes, mBoard[x][y]);

canvas.drawBitmap(bmp,null,rf,mPaint);
这将解决内存问题,即使您使用数百个图像

希望这有帮助
Jasper

此链接我的帮助您是否在数组列表中存储图像的(int)ID???为什么需要在代码中加载图像?您可以只在XML布局文件中执行此操作。无论如何,我们可能需要更多的代码来为您解决这个问题。@Haps我添加了一些额外的代码来显示what mArrayList.get(0)。getResourceId(此)正在调用。@MichellBak该应用程序的工作方式就像一个测验,用户可以从中选择4张图片。图像将根据问题的不同而变化。我从未尝试过使用SurfaceView。我将尝试做一些例子,然后看看你的建议是否有效。谢谢你的建议。
bmp = BitmapFactory.decodeResource(mRes, mBoard[x][y]);

canvas.drawBitmap(bmp,null,rf,mPaint);