Set onclicklistener on imageview in android example

Add click event method on imageView programmatically using dynamic programming coding.

SetOnClickListener() function is used to add click events on android widgets. So app developer can easily add setOnClickListener() on imageView. So here is the complete step by step tutorial for Set onclicklistener on imageview in android example.

android-project-download-code-button

How to Set onclicklistener on imageview in android example.

Copy the image inside drawable-hdpi folder.

drawable hdpi folder

Download below image and put it into drawable-hdpi folder.

new_image
Code for MainActivity.java file.

 package com.onclicklistenerimageview_android_examples.com;

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

public class MainActivity extends Activity {

 ImageView imgClick;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 imgClick = (ImageView)findViewById(R.id.imageView1);
 
 imgClick.setOnClickListener(new View.OnClickListener() {
 
 @Override
 public void onClick(View v) {
 
 Toast.makeText(MainActivity.this, "You clicked on ImageView", Toast.LENGTH_LONG).show();
 
 }
 });
 }
}

Code for activity_main.xml layout file.

<RelativeLayout 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"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context="com.onclicklistenerimageview_android_examples.com.MainActivity" >

 <ImageView
 android:id="@+id/imageView1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_centerHorizontal="true"
 android:layout_centerVertical="true"
 android:src="@drawable/new_image" />

</RelativeLayout>

Screenshot:

Set onclicklistener on imageview in android example

Click here to download Set onclicklistener on imageview in android example project.

Leave a Reply

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