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.

code:

//Imageview initialization
changeImageView=(ImageView) findViewById(R.id.changable_img);

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

@Override
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();

}
});

or

//implementing onclick listener

public class MainActivity extends Activity implements OnClickListener{

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

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

@Override
public void onClick(View v) {
ImageView tempImg=(ImageView)v;
v.setBackgroundResource(R.id.iphone);

}
}

TOP