开发者

Android:set ImageView dynamically?

开发者 https://www.devze.com 2023-02-26 14:01 出处:网络
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:

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"?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消