Changing ImageView content causes OutOfMemoryError

后端 未结 5 486
渐次进展
渐次进展 2021-02-04 02:14

I have a very simple application with one ImageView and a Button. The first Drawable resource loaded by my ImageView is specified with the \"android:src\" tag i

5条回答
  •  再見小時候
    2021-02-04 02:51

    Seems like before loading a new Bitmap I had to recycle the Bitmap displayed by the ImageView, now it is working without a problem. Hope this helps someone else, just call the folowing method before setting the new ImageView's content.

    ((BitmapDrawable)imageView.getDrawable()).getBitmap().recycle();

    so the code now looks like this:

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);
        switch(requestCode){
            case INTENT_REQUEST_SELECT_IMAGE:
                if(resultCode==Activity.RESULT_OK){
                    Uri selectedImageUri = data.getData();
                    Log.i(TAG,"selectedImageUri.getPath()"+selectedImageUri.getPath() );
                    ImageView imageView = (ImageView) this.findViewById(R.id.ImageView_of_text);
                    ((BitmapDrawable)imageView.getDrawable()).getBitmap().recycle();
                    imageView.setImageURI(selectedImageUri);
                    imageView.invalidate();
    
                }else{
                    //TODO define what to do in case the user canceled OCR or any other event
                }
                break;
            default:
                break;
        }
    }
    

    Please note the call to recycle on the Bitmap of the ImageView.

提交回复
热议问题