Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show ImageView programmatically

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!

like image 253
erdomester Avatar asked May 30 '11 21:05

erdomester


People also ask

What is ImageView code?

Displays image resources, for example Bitmap or Drawable resources. ImageView is also commonly used to apply tints to an image and handle image scaling. To learn more about Drawables, see: Drawable Resources.

How set ImageView width and height dynamically in Android?

If you want to just fit the image in image view you can use" wrap content" in height and width property with scale-type but if you want to set manually you have to use LayoutParams. Layoutparams is efficient for setting the layout height and width programmatically.


2 Answers

//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); 
like image 155
Sam Avatar answered Sep 27 '22 22:09

Sam


int id = getResources().getIdentifier("gameover", "drawable", getPackageName()); ImageView imageView = new ImageView(this); LinearLayout.LayoutParams vp =      new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,                      LayoutParams.WRAP_CONTENT); imageView.setLayoutParams(vp);         imageView.setImageResource(id);         someLinearLayout.addView(imageView);  
like image 37
hook38 Avatar answered Sep 27 '22 21:09

hook38