android - Android中如何设置imageView的背景避免OutOfMemoryError?

标签 android bitmap out-of-memory android-imageview

我尝试更改 ImageView 的背景,但由于 OutOfMemoryError 而出错。

我搜索过使用 Bitmap 更改背景,但我不知道如何使用它。

当我点击按钮时,背景会变成另一张图片。

代码如下:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View view = inflater.inflate(R.layout.user_guide, container, false) ;
        last = (Button) view.findViewById(R.id.last);
        user = (ImageView) view.findViewById(R.id.image);
        last.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                                user.setBackgroundResource(R.drawable.test1);
            }
        });

我搜索了下面的代码,但我不知道用它来改变 Imageviewbackground 是否合适。 谁能教我如何使用它?

public static Bitmap readBitMap(Context context, int resId){
         BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.RGB_565;
         opt.inPurgeable = true;
         opt.inInputShareable = true;
         InputStream is = context.getResources().openRawResource(resId);
         return BitmapFactory.decodeStream(is,null,opt);
         }

有人可以教我如何使用它来更改 ImageView 的背景并且没有 OutOfMemoryError 吗?

提前致谢。

最佳答案

试试下面的代码:

last.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                 Bitmap bitmap=readBitmap(this, R.drawable.test1);
                 image.setImageBitmap(bitmap);
                 bitmap.recycle();
                 bitmap=null;
            }
        });

使用你的方法:

public static Bitmap readBitMap(Context context, int resId){
         BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.RGB_565;
         opt.inPurgeable = true;
         opt.inInputShareable = true;
         InputStream is = context.getResources().openRawResource(resId);
         return BitmapFactory.decodeStream(is,null,opt);
         }

关于android - Android中如何设置imageView的背景避免OutOfMemoryError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21987630/

相关文章:

c++ - Qt 中的锁位。如何实现?

android - 使用 Android 自定义 Drawable

java - 如何在 android 中的图像上放置图钉标记图像?

c# - .net winform treeview 内存不足异常

android - 如何使用 Gradle 解决模块中的循环依赖?

android - 跟踪/计数以模式进行的解锁尝试

c# - 我应该处理局部类变量吗?

Java OutOfMemory 异常 : mmap error on loading zip file

android - 如何限制 LazyColumn 中的项目数?

android - 在 eclipse "Run As -> Android Application"构建中包含 Maven 依赖项