我正在尝试下载图像,并动态创建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);

10-07 13:17
查看更多