How to open the file manager and when clicking on a photo, change the src of an Imageview?

Asked

Viewed 270 times

1

I am developing an APP where it is possible to create an account, so I want to know how to click on Imageview, open the smartphone gallery, and when clicking on an image, the Imagrview src was changed to the photo that the user selected.

Thanks in advance!!

1 answer

1

First, define a standard code to identify the Intent:

private static final int PICK_IMAGE = 11;

Second, call the Intent who will be responsible for presenting the user which application he wants to open the gallery to choose the image:

Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT);
getIntent.setType("image/*");

Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
pickIntent.setType("image/*");

Intent chooserIntent = Intent.createChooser(getIntent, "Select Image");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {pickIntent});

startActivityForResult(chooserIntent, PICK_IMAGE);

After placing the code above, you need to overwrite the onActivityResult of his Activity, because this method will receive the image from the gallery:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == PICK_PHOTO && resultCode == Activity.RESULT_OK) {
        if (data == null) {
            // Nenhuma imagem selecionada...
            return;
         }

         InputStream inputStream = context.getContentResolver().openInputStream(data.getData());
         Bitmap b = BitmapFactory.decodeStream(inputStream);
         Drawable d = new BitmapDrawable(b);
         suaImageView.setImageDrawable(d);
    }
}

In the above code we receive the user selected content, first of all we test if it is really coming from your gallery call through the variable PICK_PHOTO, then we turn the InputStream received on a Bitmap, and of a Bitmap for a Drawable making it possible to use in your ImageView.


See more on the links below:

android pick images from gallery

How to create a Drawable from a stream without resizing it?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.