Android - 在填写ScrollView时获取OutOfMemory

时间:2013-12-21 21:28:13

标签: java android android-layout out-of-memory android-scrollview

我正在写一部“非常长卷轴”的游戏。游戏的主要元素是ScrollView,我填充了“块”。

一个“块”看起来像这样:


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
    <ImageView
        android:id="@+id/sec3"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="@drawable/_40" />
</LinearLayout>

图像(.jpg,720x6000)大小为800-900kb。 我正在使用以下代码填充我的ScrollView(对于一种类型的图像):


    View block_3 = inflater.inflate(R.layout.block_3, null);

    for (int i = 0; i != Blocks.block_20; i++) { //Filling the LinearLayout in ListView with 20 blocks
        LinLayout_in_ScrollView.addView(block_3, layout_params);
    }

但我的应用程序因OutOfMemory错误而崩溃。我试过使用ListView而不是ScrollView,但我失败了。我想过在ScrollView中动态加载项目,但这很难做到。那我怎么能避免OutOfMemoryException?

P.S。请原谅我的英语。

3 个答案:

答案 0 :(得分:0)

内存不足异常是处理图像时最常见,也是最棘手的问题之一。您可能想看看这个:http://developer.android.com/training/displaying-bitmaps/load-bitmap.html#load-bitmaphttp://developer.android.com/training/displaying-bitmaps/index.html。 本教程教授如何有效地加载位图/图像,还有一些示例。 您可能也希望看到这一点:Out of Memory Exception while scroll Listview?

答案 1 :(得分:0)

您正在采取的方法可能会引入其他问题以及OOM异常。 我强烈建议您查看Android SDK中提供的JetBoy示例。 首先,您可能希望使用SurfaceView代替ScrollView

答案 2 :(得分:0)

这里的问题是所有图像需要同时装入内存。很容易相信图像只使用与jpg文件一样多的内存,但它们在加载到内存时会被解码,并且在你的情况下可能会使用大约4 MiB的内存(如果我的快速计算是正确的)。

我建议你不要使用ScrollView。使用Canvas或使用OpenGL绘制图形。您很可能需要使用OpenGL在实时的侧滚动游戏中获得良好的性能(即使它只是“2D”2D)。如果你需要很多图像,那么你必须非常小心不要一次加载太多内存(不先释放内存用于其他图像)。在某些情况下使用JNI和Android NDK在本机代码中进行图像处理和渲染可能很有用,因为有时很难在Android上的Java中获得良好的实时性能而没有垃圾收集冻结,并且在加载许多图像时类似。

OpenGL需要一些工作来学习(如果你不知道),但我建议你去研究它。有关Android上OpenGL ES的概述,请查看here。它将使您在各种设备上获得出色的性能。在我看来,学习它是非常值得的。