简体   繁体   English

将图像动态设置为ImageView

[英]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. 我在布局中有一个空白的ImageView,现在我想动态地放置一个图像。 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? 有没有办法像对TextView那样对ImageView做到这一点?

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. 任何帮助深表感谢。

Try this 尝试这个

image.setImageResource(R.drawable.yourimage);

or 要么

image.setImageDrawable(getResources().getDrawable(R.drawable.yourimage);
image.setImageResource(int resId)

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);

To avoid every problem you can use the sure way 为了避免每一个问题,您可以使用确定的方法

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM