Android:动态设置ImageView?

标签 android layout dynamic imageview android-linearlayout

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

相关文章:

html - 使用 <table> 或 <ul> 列表更合适?

c++ - 访问动态二维字符数组 C++

javascript - Youtube API 检测自动播放是否被禁用

android - Galaxy s3 和 AppWidgets : OnAppWidgetOptionsChanged min and max dimensions

java - 将 Cursor 转换为通用对象 android

c++ - 从友元函数返回后无法输出动态数组

html - 左侧 div 侧边栏动态向下延伸到底部

android - 如何在 Android 上播放合成声音?

.net - WPF 文本框太大

android - 使父布局背景变暗/模糊