Android默认内部加载图片是以ARGB_8888格式的位图来加载所有图像的,这就意味着,每一个像素需要用4个字节来表述。例如,一个800*400像素的图像需要800*400*4=1536000字节,大约1.5MB。

一个1280 × 712 像素的图像,需要1280*712*4=3545440字节=3.56MB。

性能考虑,android为了提高效率,Bitmap真正的位图数据是在ndk中用c写的。所以用setCallback是不能销毁位图数据的,应该调用Bitmap的recycle()来清理内存。

Layout布局文件中定义的背景,Android默认是缓存并没有销毁的。

所以需要能销毁内存中的背景图,需要做如下处理。

布局文件

注意这里定义了id,同时没有用android:background定义背景

<?xmlversion="1.0"encoding="utf-8"?>

<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"

android:id="@+id/rootView"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:orientation="horizontal">

<!-- android:background="@drawable/splash" -->

</LinearLayout>

定义背景是通过下面代码定义的:

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.splash);

// http://blog.csdn.net/micro_rat/article/details/6307067

LinearLayout rootView = (LinearLayout) this.findViewById(R.id.rootView);

Bitmap bm = BitmapFactory.decodeResource(this.getResources(), R.drawable.splash);

BitmapDrawable bd = new BitmapDrawable(this.getResources(), bm);

rootView.setBackgroundDrawable(bd);

}

销毁图片资源用下面代码:

@Override

protected void onDestroy() {

// http://blog.csdn.net/micro_rat/article/details/6307067

LinearLayout rootView = (LinearLayout) this.findViewById(R.id.rootView);

BitmapDrawable bd = (BitmapDrawable)rootView.getBackground();

bd.setCallback(null);

bd.getBitmap().recycle();

super.onDestroy();

}

不能用Layout上定义布局,onDestroy 销毁图片,是因为Layout布局上定义时,会自动从缓存中取数据,而我们销毁了这时候会报错误:“try to use a recycled bitmap"的异常。上面的代码书写方式才不会报错。

参考资料

关于android中使用很多大图片的一些做法
http://blog.csdn.net/micro_rat/article/details/6307067

http://stackoverflow.com/questions/10661894/xml-menu-background-memory-issues

更多相关文章

  1. Android 中LayoutInflater(布局加载器)源码篇之createViewFromTag
  2. TabHost和android:layout_height="0.0dip"以及android:layout_we
  3. Android 自定义控件外观
  4. android 自定义spinner
  5. Android弹出键盘布局闪动原理和解决
  6. Android学习笔记(二) 布局方式的介绍
  7. Android自定义扁平化对话框
  8. Android横竖屏布局总结

随机推荐

  1. Android危险权限和权限组
  2. 【android studio】导入项目后无法运行,修
  3. swig android的使用
  4. android 源码获取
  5. Delphi XE5 android 捕获几个事件
  6. android之渐变色背景
  7. 如何实现Android重启应用程序代码 ?
  8. android反射方式访问内部类成员
  9. android RecyclerView checkbox复用解决
  10. 【Android】Activity遮罩效果的实现