2012-05-28 53 views
0

我正在爲平板電腦(1024x768)開發Android應用程序。我在這裏搜索並找到一些解決方案,但任何人都解決了我的問題。該應用程序有5個屏幕和每個屏幕有我加載的ImageView:Android:加載圖像時出錯:OutOfMemoryError:位圖大小超過虛擬機預算

<ImageView 
    android:id="@+id/imageView1" 
    android:layout_width="1024dp" 
    android:layout_height="768dp" 
    android:layout_centerHorizontal="TRUE" 
    android:src="@drawable/scene1" 
    /> 

第一和第二屏負載不錯,但是當我嘗試加載第三個,我收到以下錯誤(每屏我通過startActivity負載這是它的佈局不是一個佈局錯誤,因爲如果我用不同的順序加載它們,我可以裝載兩個,第三個crases太):

05-28 17:03:51.774: E/AndroidRuntime(401): java.lang.RuntimeException: Unable to start activity ComponentInfo{xxx}: android.view.InflateException: Binary XML file line #10: Error inflating class <unknown> 

05-28 17:03:51.774: E/AndroidRuntime(401): Caused by: android.view.InflateException: Binary XML file line #10: Error inflating class <unknown> 


05-28 17:03:51.774: E/AndroidRuntime(401): Caused by: java.lang.reflect.InvocationTargetException 


05-28 17:03:51.774: E/AndroidRuntime(401): Caused by: java.lang.OutOfMemoryError: bitmap size exceeds VM budget 

我試過幾件事情:

@Override 
    public void onPause() 
    { 
    super.onPause(); 
    Log.i("URI", "Syste.gc"); 
    // yada yada yada... 

    System.gc(); 
    } 

@Override 
protected void onDestroy() 
{ 
    super.onDestroy(); 

    unbindDrawables(findViewById(R.id.RootView)); 
    System.gc(); 
} 

private void unbindDrawables(View view) 
{ 
    if (view.getBackground() != null) 
    { 
     view.getBackground().setCallback(null); 
    } 
    if (view instanceof ViewGroup) 
    { 
     for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) 
     { 
      unbindDrawables(((ViewGroup) view).getChildAt(i)); 
     } 
     ((ViewGroup) view).removeAllViews(); 
    } 
} 

但我總是得到錯誤。

圖像是PNG,其重量低於50k。

有什麼建議嗎?

謝謝!

+0

圖像的文件大小几乎是不相關的。像素的寬度和高度是多少? –

+0

1024x768是寬度和高度,但我需要圖像來填充所有屏幕... – oriolpons

回答

1

嘗試在onCreate()方法中加載圖像,而不是從XML加載圖像。

您是否嘗試先讀取圖像的尺寸和類型,然後加載該圖像的縮小版?

由於Android developer resources建議。

+0

就是這樣。我用:\t公共靜態位圖decodeSampledBitmapFromResource(資源RES,INT渣油,詮釋reqWidth, \t INT reqHeight) { \t //首先解碼與inJustDecodeBounds = true來檢查尺寸 \t最後BitmapFactory.Options選項=新BitmapFactory.Options (); \t選項。inJustDecodeBounds = true; \t BitmapFactory.decodeResource(res,resId,options); \t //計算樣本大小 \t options.inSampleSize = calculateInSampleSize(options,reqWidth,reqHeight); \t //使用inSampleSize解碼位圖集 \t options.inJustDecodeBounds = false; \t return BitmapFactory.decodeResource(res,resId,options); \t} – oriolpons

0

首先,調用System.gc()不會真的使垃圾收集器通過,它可以真正阻礙你的性能,所以我會限制自己使用它如此廣泛。如果您希望垃圾收集器清理圖像,請使用WeakReferences,並將圖像存儲在HashMap中。

其次,嘗試使用更小的圖像,因爲虛擬機會快速崩潰。

1

1024x768是DP中的尺寸,像素數可能高達高分辨率設備的兩倍。

如果您使用bitmapfactory解碼1024x768圖像,它將根據密度縮放位圖,因此最終可能會生成2048x1536的圖像,這會佔用12MB的大小。

如果您始終希望無論設備分辨率如何,圖像都是相同分辨率,而不是放在Drawable-nodpi文件夾中,這會導致其在解碼時不能調整大小。

相關問題