Skip to content
This repository has been archived by the owner on Oct 20, 2022. It is now read-only.

Latest commit

 

History

History

selecting_a_gallery_image

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
id title brief sdk
E43B67D6-25DA-87AF-1046-E9ACB6FE4110
Selecting a Gallery Image
This recipe shows how to read an image from the gallery and display it in an ImageView.

Recipe

  1. Add an ImageView to Main.axml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
 <Button  
    android:id="@+id/myButton"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Pick an image from the gallery"/>
 <ImageView
    android:id="@+id/myImageView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>
&lt;/LinearLayout&gt;</code></pre>
  1. In an Activity subclass, create an Intent with a MIME type set to “image/*” and an action set to ActionGetContent. Pass the intent to a StartActivityForResult method call.
button.Click += delegate {
    var imageIntent = new Intent ();
    imageIntent.SetType ("image/*");
    imageIntent.SetAction (Intent.ActionGetContent);
    StartActivityForResult (
        Intent.CreateChooser (imageIntent, "Select photo"), 0);
};
  1. Override OnActivityResult and set the image Uri of the ImageView to the Uri of the selected image.
protected override void OnActivityResult (int requestCode, Result resultCode, Intent data)
{
    base.OnActivityResult (requestCode, resultCode, data);

    if (resultCode == Result.Ok) {
        var imageView =
            FindViewById&lt;ImageView&gt; (Resource.Id.myImageView);
        imageView.SetImageURI (data.Data);
    }
}

Note that no image is shown initially until it is selected from the gallery. Once selected, the image appears on the screen as shown above.

Additional Information

The Data property of the Intent returned to OnActivityResult will contain the Uri of the selected image. We check the result in case the user cancelled the selection.