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. |
|
- 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"/>
</LinearLayout></code></pre>
- In an Activity subclass, create an Intent with a MIME type set to “image/*” and an action set to
ActionGetContent
. Pass the intent to aStartActivityForResult
method call.
button.Click += delegate {
var imageIntent = new Intent ();
imageIntent.SetType ("image/*");
imageIntent.SetAction (Intent.ActionGetContent);
StartActivityForResult (
Intent.CreateChooser (imageIntent, "Select photo"), 0);
};
- Override
OnActivityResult
and set the image Uri of theImageView
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<ImageView> (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.
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.