Android:set ImageView dynamically?

只愿长相守 提交于 2020-01-13 06:29:43

问题


I'm trying to download an image, and create an ImageView dynamically and add it to my layout, but it won't display the image. Here is my code:

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

maybe I need to refresh the layout after I add the ImageView? How do you "refresh"?


回答1:


Try the following code, and you will not need to refresh. Put your image url into the inputurl variable.

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



回答2:


I think u have to deifne the parameters for the vp

if u will define parameters it will display the image like-

LinearLayout.LayoutParams Params=new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
        Params.setMargins(0,0,0,0);

        Params=new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);



回答3:


You can use another thread to download the image, and after download finishes you can update the drawable by using a handler. You can see how to make another thread at the documentation. It does not seems easy but it would be better to learn how to do it, if you want to build more responsive android apps.

(title) Example ProgressDialog with a second thread http://developer.android.com/guide/topics/ui/dialogs.html



来源:https://stackoverflow.com/questions/5676575/androidset-imageview-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!