How to create an imageview and implement it’s onclicklistener dynamically?

by / Monday, 05 August 2013 / Published in Android

ImageView displays an arbitrary image, such as an icon. The ImageView class can load images from various sources (such as resources or content providers), takes care of computing its measurement from the image so that it can be used in any layout manager, and provides various display options such as scaling and tinting.

Here we show how to create an imageview and its attribute and apply onclicklistener annonymous class to create an event.


//Imageview initialization
changeImageView=(ImageView) findViewById(;

//Image click listener
changeImageView.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
changeImageView.setBackgroundResource(R.drawable.animal_logo10);//set imageview background
Toast.makeText(MainActivity.this, "Image has been changed.", Toast.LENGTH_LONG).show();



//implementing onclick listener

public class MainActivity extends Activity implements OnClickListener{

protected void onCreate(Bundle savedInstanceState) {

ImageView img=new ImageView(this);//create imageview object programmatically
img.setBackgroundResource(R.drawable.ic_launcher);//set background image
img.setOnClickListener(this);//unimplemented method

public void onClick(View v) {
ImageView tempImg=(ImageView)v;