我正在尝试下载图像,动态创建 ImageView 并将其添加到我的布局中,但它不会显示图像。这是我的代码:
ImageView image = new ImageView(this);
LinearLayout.LayoutParams vp = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
image.setLayoutParams(vp);
image.setScaleType(ImageView.ScaleType.CENTER_CROP);
image.setMaxHeight(50);
image.setMaxWidth(50);
image.setImageDrawable(avatar);
theLayout.addView(image);
也许我需要在添加 ImageView 后刷新布局?你如何“刷新”?
最佳答案
试试下面的代码,你就不需要刷新了。将您的图片网址放入 inputurl
变量。
InputStream is = null;
String inputurl = " Enter url of ur image ";
try {
URL url = new URL(inputurl);
Object content = url.getContent();
is = (InputStream) content;
avatar = Drawable.createFromStream(is,"src");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ImageView image = new ImageView(this);
LinearLayout.LayoutParams vp = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
image.setLayoutParams(vp);
image.setScaleType(ImageView.ScaleType.CENTER_CROP);
image.setMaxHeight(50);
image.setMaxWidth(50);
image.setImageDrawable(avatar);
theLayout.addView(image);
关于Android:动态设置ImageView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5676575/