繁体   English   中英

将图像动态设置为ImageView

[英]Setting an Image to ImageView dynamically

如果这是重复的帖子,请原谅我,但我尝试过并且找不到关于此主题的任何内容。 我在布局中有一个空白的ImageView,现在我想动态地放置一个图像。 既然有

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

有没有办法像对TextView那样对ImageView做到这一点?

即...

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

任何帮助深表感谢。

尝试这个

image.setImageResource(R.drawable.yourimage);

要么

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

如果要在手机上显示图像文件,可以执行以下操作:

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

如果要显示可绘制资源中的图像,请执行以下操作:

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

为了避免每一个问题,您可以使用确定的方法

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