Show ImageView programmatically

erdomester picture erdomester · May 30, 2011 · Viewed 147.3k times · Source

How can I make an ImageView appear in the middle of the screen when the user clicks a button? I have placed the image in the res/drawable-folder.

I've been trying with the code below but I don't know how to make the ImageView appear:

 View v = new ImageView(getBaseContext());
 ImageView image; 
 image = new ImageView(v.getContext()); 
 image.setImageDrawable(v.getResources().getDrawable(R.drawable.gameover));

Thanks!

Answer

Sam picture Sam · Oct 8, 2012
//LinearLayOut Setup
LinearLayout linearLayout= new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);

linearLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));

//ImageView Setup
ImageView imageView = new ImageView(this);

//setting image resource
imageView.setImageResource(R.drawable.play);

//setting image position
imageView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 
LayoutParams.WRAP_CONTENT));

//adding view to layout
linearLayout.addView(imageView);
//make visible to program
setContentView(linearLayout);