Android ImageView ImageButton Example

Filed Under: Android

Android ImageView is used to display an image file. Android also has an ImageButton. As the name suggests, the ImageButton component is a button with an image on. The ImageButton is represented by the Android class android.widget.ImageButton. In this tutorial we’re going to implement both android ImageView and ImageButton in our application.

Android ImageView

Android ImageView is one of the UI widget that is used to display images in the application. It’s defined in the XML layout in the following manner.


<ImageView
            android:id="@+id/imageView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:src="@drawable/ic_launcher" />

Here android:src is used to assign the image file from the drawable resource folder.

Android ImageView ScaleType

ImageView in android comes with different configuration options to support different scaleTypes.

scaleType options are used for scaling the bounds of an image to the bounds of image view. Below are the listed scaleType configuration properties supported.

  1. CENTER : Displays the image centered in the view with no scaling.
  2. CENTER_CROP : Scales the image such that both the x and y dimensions are greater than or equal to the view, while maintaining the image aspect ratio; centers the image in the view
  3. CENTER_INSIDE : Scales the image to fit inside the view, while maintaining the image aspect ratio. If the image is already smaller than the view, then this is the same as center
  4. FIT_CENTER : Scales the image to fit inside the view, while maintaining the image aspect ratio. At least one axis will exactly match the view, and the result is centered inside the view
  5. FIT_START : Same as fitCenter but aligned to the top left of the view
  6. FIT_END : Same as fitCenter but aligned to the bottom right of the view
  7. FIT_XY : Scales the x and y dimensions to exactly match the view size. dDoes not maintain the image aspect ratio
  8. MATRIX : Scales the image using a supplied Matrix class. The matrix can be supplied using the setImageMatrix method. A Matrix class can be used to apply transformations such as rotations to an image

The default scaleType in FIT_CENTER.

Note: The fitXY scale type allows you to set the exact size of the image in your layout. However, there can occur potential distortions of the image due to scaling. For example;


<ImageView
            android:id="@+id/imageView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:scaleType="fitXY"
            android:src="@drawable/ic_launcher" />

Supporting Multiple Densities in android ImageView

There is a powerful system for selecting the correct image asset for the correct device. There are specific drawable folders for each device density category including: ldpi (low), mdpi (medium), hdpi (high), and xhdpi (extra high) etc. For example, a drawable-mdpi stands for drawable medium dots per inch.

In this project we’ll show various image scaleTypes in the activity along with an android Image Button.

Adding Image to Resources

We’ll use ImageView to display a “png” image. PNGs are lossless, so they have that advantage over JPG images. We add our images into folder “res/drawable-xdpi“, “res/drawable-mdpi” or “res/drawable-hdpi“ etc. depending on the size of the image.

Android ImageView, ImageButton Example Project Structure

android imageview imagebutton example project

As you can see we’ve added a balloon.png file to drawable folders of respective dimensions.

Android ImageView Project Code

The xml layout file contains five images with different scaleTypes along with an ImageButton. The layout is a child of a ScrollView (to make the activity scrollable) which we’ll discuss later.

activity_main.xml


<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:src="@drawable/balloon" />

        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:background="#fff"
            android:padding="3dp"
            android:scaleType="fitXY"
            android:src="@drawable/balloon" />

        <ImageView
            android:id="@+id/imageView3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:background="#fff"
            android:paddingBottom="50dp"
            android:paddingLeft="3dp"
            android:paddingRight="3dp"
            android:paddingTop="3dp"
            android:scaleType="fitStart"
            android:src="@drawable/balloon" />


        <ImageView
            android:id="@+id/imageView4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:background="#fff"
            android:paddingBottom="50dp"
            android:paddingLeft="3dp"
            android:paddingRight="3dp"
            android:paddingTop="3dp"
            android:scaleType="fitEnd"
            android:src="@drawable/balloon" />

        <ImageView
            android:id="@+id/imageView5"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:background="#fff"
            android:padding="3dp"
            android:src="@drawable/balloon" />


        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/imageButton"
            android:layout_gravity="center_horizontal"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true"
            android:src="@android:drawable/ic_menu_send"/>

    </LinearLayout>

</ScrollView>

The MainActivity.java is defined below.


package com.journaldev.imageview;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // setting image resource from drawable
        ImageView imageView = (ImageView) findViewById(R.id.imageView2);
        imageView.setImageResource(R.drawable.balloon);

        imageView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Toast.makeText(getApplicationContext(), "Clicked Second Image",
                        Toast.LENGTH_SHORT).show();
            }
        });

        ImageButton imageButton=(ImageButton) findViewById(R.id.imageButton);
        imageButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(), "Clicked Image Button",
                        Toast.LENGTH_SHORT).show();
            }
        });

        Bitmap bMap = BitmapFactory.decodeResource(getResources(), R.drawable.balloon);
        Bitmap bMapScaled = Bitmap.createScaledBitmap(bMap, 350, 300, true);
        ImageView image = (ImageView) findViewById(R.id.imageView5);
        image.setImageBitmap(bMapScaled);

    }
}

Here we’ve made the second ImageView clickable to display a Toast.

Android ImageButton

Android ImageButton has all the properties of a normal button. It has the option to add a resource file instead of text.

Working with Bitmaps

Bitmaps belong to the class android.graphics.Bitmap.

Bitmapfactory is mainly used for Scaling images from the drawable. If we don’t use BitmapFactory then it leads to insufficient memory allocations.

We can change the bitmap displayed in an ImageView to a drawable resource as it’s done for imageview2 in the code above.


ImageView image = (ImageView) findViewById(R.id.imageview2);
image.setImageResource(R.drawable.balloon);

The imageview5 is not assigned any scaleType so we’ve scaled it using a static method createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, boolean filter)

To pass any file present in the storage into imageview the following code is implemented.


ImageView image = (ImageView) findViewById(R.id.test_image);
Bitmap bMap = BitmapFactory.decodeFile("/sdcard/test.png");
image.setImageBitmap(bMap);

setImageBitmap() sets the bitmap content to the ImageView.

The image representing the final output is shown below:
android imageview, android imagebutton

  1. The first ImageView is not assigned any scaleType by default. Hence center being the default scaleType is implicitly assigned to it.
  2. The second ImageView has the scaleType fitXY. A distortion is seen, hence its not a good practice to use in applications.
  3. The third and fourth ImageViews have scaleType fitStart and fitEnd respectively.
  4. The fifth ImageView has been scaled with custom widths and heights using Bitmaps.

Here is a short animation of our app too.

android imageview example, android ImageButton

This brings an end to this tutorial. You can download the final Android ImageView project from the below link.

Reference: Official Doc

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages