【发布时间】:2011-05-29 19:32:51
【问题描述】:
我想将 8 个图像缩略图放在一条水平线上,使用整个可用宽度。
图像是从允许我指定尺寸的网络服务中检索的。
我尝试了以下方法:
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);
}
LinearLayout thumbs 设置了 android:layout_width="fill_parent。这段代码生成的 thumbs 明显小于宽度的 1/8。这是为什么?正确的方法是什么?
更新:
此代码位于片段的 onCreateView 内。虽然我的宽度值是根据根视图计算的并且是正确的,但 thumbs.getWidth() 返回 0,尽管视图之前已膨胀并且宽度也应该为 480,因为设置了 layout_width填充父级。我不确定这是否有问题。
我的假设是否正确,即创建的 ImageViews 的布局默认设置为 wrap_content ?如果没有,如何用Java代码设置?
【问题讨论】:
-
什么是容器?
container.getWidth();得到的号码是多少? -
这里的容器是一个 FrameLayout,它充当此代码所在片段的根。 getWidth() 正确返回 480,因此单个拇指为 60x60px。这是否与 px / dip 转换有关?
-
如果你使用
thumbs.addView (iv, new LayoutParams(thumbSize, thumbSize);,它的尺寸是否合适? -
是的,确实如此。所以我猜 wrap_content 不是默认布局。默认布局是什么? Java中如何改成wrap_content?
-
我回答了你新问题的最后一部分