Android ImageView Example

An ImageView is an user interface element for displaying an image. Now let’s create an app which displays an image, and toasts a message “Welcome to the App” when the image is clicked.

Step 1: Create a new project with name imageviewexample and package name com.myexample.imageview. Select File -> New -> New Project. Fill the forms and click “Finish” button.

Step 2: In app level build.gradle add appcompat-v7 dependency:

dependencies {
    compile 'com.android.support:appcompat-v7:27.+'
    compile fileTree(dir: 'libs', include: ['*.jar'])
}

Step 3: In the app/src/main/res/drawable/ folder of the project, add the image to be displayed. Let it be ‘myimage.jpg’. (The drawable folder can have different names: drawable-hdpi, drawable-mdpi, drawable-ldpi, drawable-xhdpi, drawable-xxhdpi, etc.)

Step 4: Open res -> layout -> xml (or) main.xml and add following code. Here we will create an ImageView in a RelativeLayout.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:padding="16dp"> 
 
    <ImageView 
	        android:id="@+id/imageview1" 
	        android:layout_width="wrap_content" 
	        android:layout_height="wrap_content" 
	        android:layout_centerHorizontal="true" 
	        android:src="@drawable/myimage"/> 

</RelativeLayout> 

Step 5: Open app -> java -> package and open MainActivity.java. Add following code in it. Here we will add a TextChangedListener to the EditText. When anything is written in EditText, we will convert that text to a String and display it in a TextView.

package com.myexample.imageview;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {

private ImageView imageview1;

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        imageview1 = (ImageView) findViewById(R.id.imageview1);

        imageview1.setOnClickListener(new View.OnClickListener() { 
	            @Override 
	            public void onClick(View v) { 
	                Toast.makeText(getApplicationContext(), "Welcome to the App",
                     Toast.LENGTH_SHORT).show(); 
	            } 
	        });
    }

}

Output:

Now run the app. You will see your image in ImageView. When you click the image,it will toast the message “Welcome to the App”.