Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Using ImageView

An ImageView control is used to display images in Android applications. An image can be displayed by assigning it to the ImageView control and including the android:src attribute in the XML definition of the control. Images can also be dynamically assigned to the ImageView control through Java code.

A sample ImageView tag when used in the layout file is shown here:

<ImageView
    android:id="@+id/first_image"
    android:src = "@drawable/bintupic"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:scaleType="fitXY"
    android:adjustViewBounds="true"
    android:maxHeight="100dip"
    android:maxWidth="250dip"
    android:minHeight="100dip"
    android:minWidth="250dip"
    android:resizeMode="horizontal|vertical" />

Almost all attributes that we see in this XML definition should be familiar, with the exception of the following ones:

  • android:src—Used to assign the image from drawable resources. We discuss drawable resources in detail in Chapter 4. For now, assume that the image in the res/drawable folder is set to display through the ImageView control via this attribute.

    Example:

    android:src = "@drawable/bintupic"

    You do not need to specify the image file extension. JPG and GIF files are supported, but the preferred image format is PNG.

  • android:scaleType—Used to scale an image to fit its container. The valid values for this attribute include fitXY, center, centerInside, and fitCenter. The value fitXY independently scales the image around the X and Y axes without maintaining the aspect ratio to match the size of container. The value center centers the image in the container without scaling it. The value centerInside scales the image uniformly, maintaining the aspect ratio so that the width and height of the image fit the size of its container. The value fitCenter scales the image while maintaining the aspect ratio, so that one of its X or Y axes fits the container.
  • android:adjustViewBounds—If set to true, the attribute adjusts the bounds of the ImageView control to maintain the aspect ratio of the image displayed through it.
  • android:resizeMode—The resizeMode attribute is used to make a control resizable so we can resize it horizontally, vertically, or around both axes. We need to click and hold the control to display its resize handles. The resize handles can be dragged in the desired direction to resize the control. The available values for the resizeMode attribute include horizontal, vertical, and none. The horizontal value resizes the control around the horizontal axis, the vertical value resizes around the vertical axis, the both value resizes around both the horizontal and vertical axes, and the value none prevents resizing.
  • + Share This
  • 🔖 Save To Your Account