Changing ImageView content causes OutOfMemoryError

后端 未结 5 482
渐次进展
渐次进展 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:37

    only use this before update imageview: imageView1.setImageURI(null);

    0 讨论(0)
  • 2021-02-04 02:41

    This was driving me nuts.

    I'm building for a Xoom with very large, hi-res, full screen images (800x1232).

    The following code worked for me:

    public void onStop()
    {
        super.onStop();
        imageView.setImageBitmap(null);
    }
    

    Good luck!!!

    0 讨论(0)
  • 2021-02-04 02:45

    I used every solution of this post and many more but no one worked.Finally I used android:largeHeap="true" in manifest and that solves my problem.

    Hope this helps someone.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-04 03:03

    The problem has now been solved. rather than only one line:

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

    add this code before updating ImageView content:

    Drawable toRecycle= gallerypic.getDrawable();
    if (toRecycle != null) {
        ((BitmapDrawable)gallerypic.getDrawable()).getBitmap().recycle();
    }
    gallerypic.setImageURI(selectedimage);
    
    0 讨论(0)
提交回复
热议问题