Cross Platform
Android
iOS
 

Display An Image

This recipe shows how to display an image using an ImageView.

Recipe



  1. Create a new Xamarin.Android application named DisplayAnImage.
  2. Add two images named sample1.png and sample2.png respectively under the Resources > drawable folder in your IDE.
  3. Replace the contents of Main.axml with the following,
<?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="@string/changeImage"/>  
    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/demoImageView"
        android:src="@drawable/sample1"        
        android:scaleType="fitCenter"/>
</LinearLayout>
  1. Add the following string to Strings.xml.
<string name="changeImage">Change Image</string>
  1. In MainActivity.cs, add code to set the ImageView’s image in the button.Click event handler.
button.Click += delegate {
       var imageView =
              FindViewById<ImageView> (Resource.Id.demoImageView);
       imageView.SetImageResource (Resource.Drawable.sample2);
}            };

Additional Information

The ImageView class allows you to display an image either declaratively in XML using the android:src attribute, or in code by calling SetImageResource.