Set size of ImageView in px at runtime
I want to put 8 image thumbs in one horizontal line, using the whole available width.
The images are retrieved from a webservice which lets me specify the dimensions. I tried the following:int widthPx = container.getWidth();
LinearLayout thumbs = (LinearLayout)curView.findViewById(R.id.thumbs);
for(int i=0; i<pics.length; i++) {
ImageView iv = new ImageView(mContextt);
int thumbSize = widthPx / 8;
try {
String url = "http://someurl/" + pics[i] + "&width=" + thumbSize + "&height=" + thumbSize;
URL imgUrl = new URL(url);
Drawable imgD = Drawable.createFromStream(imgUrl.openStream(), "src");
iv.setImageDrawable(imgD);
}
catch (Exception e) {
Log.e(TAG, "loading image failed");
e.printStackTrace();
}
thumbs.addView(iv);
}
The LinearLayout thumbs has android:layout_width="fill_parent set. The thumbs produced by this code are significantly smaller then 1/8 of the width. Why is this? What would be the correct way?
Update: This code is inside onCreateView of a F开发者_开发百科ragment. While my width value is calculated based on the root-view and is correct, thumbs.getWidth() returns 0, although the view is inflated before and should also have a width of 480 because of layout_width is set to fill_parent. I'm not sure if that's a problem.Is my assumption correct that the layout of the created ImageViews is set to wrap_content by default? If not, how to set this with Java code?
Add the ImageView
s with a fixed size, i.e.:
thumbs.addView (iv, new LayoutParams(thumbSize, thumbSize));
To answer (partially) the questions in the comments:
The ImageView API says:
takes care of computing its measurement from the image so that it can be used in any layout manager
so it is probably assuming 60px for a 160 dpi (I may be wrong there).
I'd suggest using this:
widthPx = getWindowManager().getDefaultDisplay().getWidth();
精彩评论