Android:set ImageView dynamically?

末鹿安然 提交于 2019-12-04 20:18:27
Nirav Dangi

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

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

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

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