MaxK
MaxK

Reputation: 437

Setting an Image to ImageView dynamically

Please forgive me if this is a duplicate post but I tried and could not find anything on this subject. I have a blank ImageView in a layout and now I want to put an image there dynamically. Since there is

TextView txt = (TextView) findViewById(R.id.textView1);
txt.setText("my text");

is there a way to do it for an ImageView like the way you would do it for a TextView?

ie...

ImageView image = (ImageView) v.findViewById(R.id.pPicture);
image.setImage(R.drawable.myImage); // I know this isn't correct.

Any help is much appreciated.

Upvotes: 0

Views: 194

Answers (4)

Pragnani
Pragnani

Reputation: 20145

Try this

image.setImageResource(R.drawable.yourimage);

or

image.setImageDrawable(getResources().getDrawable(R.drawable.yourimage);

Upvotes: 2

Festus Tamakloe
Festus Tamakloe

Reputation: 11310

To avoid every problem you can use the sure way

Resources res = getActivity().getResources();
 Drawable drawable= res.getDrawable(R.drawable.myImage);
 image.setImageDrawable(drawable);

Upvotes: 1

Himanshu
Himanshu

Reputation: 378

If you want to display an image file on the phone, you can do this:

private ImageView imgView;
imgView = (ImageView) findViewById(R.id.imageViewId);
imgView.setImageBitmap(BitmapFactory.decodeFile("pathToImageFile"));

If you want to display an image from your drawable resources, do this:

private ImageView imgView;
imgView = (ImageView) findViewById(R.id.imageViewId);
imgView.setImageResource(R.drawable.imageFileId);

Upvotes: 1

Justin Vartanian
Justin Vartanian

Reputation: 1149

image.setImageResource(int resId)

Upvotes: 1

Related Questions