【问题标题】:OutOfMemory Exception for background image of a layout布局背景图像的 OutOfMemory 异常
【发布时间】:2016-01-01 03:01:11
【问题描述】:

我是 android 新手,遵循 this 在 android 中创建 MEME 应用程序的教程一切正常,直到我将图像添加到片段的 RelativeLayout 背景。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:background="@drawable/dp"
    android:id="@+id/imageOut">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="@string/topText"
        android:id="@+id/topMemeText"
        android:layout_marginTop="32dp"
        android:textColor="#FFF"
        android:gravity="center_horizontal"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />


    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="@string/bottomText"
        android:id="@+id/bottomMemeText"
        android:layout_marginBottom="69dp"
        android:textColor="#FFF"
        android:gravity="center_horizontal"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

错误是

 Caused by: java.lang.OutOfMemoryError: Failed to allocate a 86687164 byte allocation with 1048576 free bytes and 63MB until OOM

我知道这个问题是由于图像大小造成的,我必须对其进行解码,因为我在网上搜索了很多案例,在这里http://developer.android.com/training/displaying-bitmaps/load-bitmap.html。但是我遇到的每个案例都使用 ImageView,但我有一个背景图像布局而不是 ImageView 所以我如何从布局中获取 ImageView 对象以便我可以使用。

mImageView.setImageBitmap(
    decodeSampledBitmapFromResource(getResources(), R.id.myimage, 100, 100));

谢谢

【问题讨论】:

  • 您使用的图片的像素大小是多少?
  • 尺寸为262kb 我知道如果我使用小尺寸图片,问题可能会解决,但我如何使用像素代码处理它1790 x 1757
  • 但是像素大小(图像的尺寸)是多少?
  • @UdiI 它的1790 x 1757
  • 图片位于哪个 Drawable 中,您在哪个设备上尝试过?

标签: java android image memory bitmap


【解决方案1】:

我的猜测是图像的大小调整导致了您的问题。

尝试将图像添加到 drawable-xxhdpi 中,看看是否有帮助。

如果它不尝试drawable-nodpi。

【讨论】:

  • thaku 你非常喜欢drawable-xxhdpi 谢谢你的所有努力,这意味着我已经尝试了好几天了,这很容易再次感谢你。你能解释一下为什么更改文件夹有效我只是这方面的初学者
  • 因为您尝试的设备是 xxhdpi,而默认的基本 Android 密度是 mdpi,因此导致操作系统对已经很大的图像进行重大调整。
【解决方案2】:
First get the bitmap 
Bitmap bitmap = decodeSampledBitmapFromResource(getResources(), R.id.myimage, 100, 100);

Convert the bitmap to drawable as follows
Drawable mDrawable = new BitmapDrawable(getResources(), bitmap);

Finally you can use mDrawable to set your relative layout background

【讨论】:

  • 其他使用解决方案对我有用,但我也在尝试您的解决方案,我正在做 `layout.setBackgroundDrawable(mDrawable);` 但这已被贬低。我是新手,您能帮忙
  • setbackground 工作在 api 级别 16 及以下 setbackgrounddrawabale
猜你喜欢
  • 2017-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-28
  • 2014-08-10
  • 1970-01-01
  • 1970-01-01
  • 2012-09-02
相关资源
最近更新 更多