Android 更新layoutParams不起作用
我正在尝试计算此图像的尺寸,它将使用以下行从web下载Android 更新layoutParams不起作用,android,android-imageview,Android,Android Imageview,我正在尝试计算此图像的尺寸,它将使用以下行从web下载imgLoader.DisplayImage(url,R.drawable.thumbnail\u background,image)。 问题是orgHeight变成了零,你不能除以零。但是为什么这是orghight0 // Add the imageview and calculate its dimensions //assuming your layout is in a LinearLayout as its root
imgLoader.DisplayImage(url,R.drawable.thumbnail\u background,image)代码>。
问题是orgHeight变成了零,你不能除以零。但是为什么这是orghight
0
// Add the imageview and calculate its dimensions
//assuming your layout is in a LinearLayout as its root
LinearLayout layout = (LinearLayout)findViewById(R.id.layout);
ImageView image = (ImageView)findViewById(R.id.photo);
ImageLoader imgLoader = new ImageLoader(getApplicationContext());
imgLoader.DisplayImage(url, R.drawable.thumbnail_background, image);
int newHeight = getWindowManager().getDefaultDisplay().getHeight() / 2;
int orgWidth = image.getWidth();
int orgHeight = image.getHeight();
//double check my math, this should be right, though
int newWidth = (int) Math.floor((orgWidth * newHeight) / orgHeight);
//Use RelativeLayout.LayoutParams if your parent is a RelativeLayout
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
newWidth, newHeight);
image.setLayoutParams(params);
image.setScaleType(ImageView.ScaleType.CENTER_CROP);
layout.updateViewLayout(image, params);
我的imageView xml如下所示:
<ImageView
android:id="@+id/photo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
/>
视图尚未放置在onCreate()
方法中,因此其尺寸为0。从onCreate()
发布一个Runnable
,以获得正确的值:
image.post(new Runnable() {
@Override
public void run() {
int newHeight = getWindowManager().getDefaultDisplay().getHeight() / 2;
int orgWidth = image.getWidth();
int orgHeight = image.getHeight();
//double check my math, this should be right, though
int newWidth = (int) Math.floor((orgWidth * newHeight) / orgHeight);
//Use RelativeLayout.LayoutParams if your parent is a RelativeLayout
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
newWidth, newHeight);
image.setLayoutParams(params);
image.setScaleType(ImageView.ScaleType.CENTER_CROP);
layout.updateViewLayout(image, params);
}
});
布局完成后,还可以使用ViewTreeObserver获取值
Ref-谢谢,它可以工作,但现在我又有一个问题,图片的高度计算不正确,我有-看起来像-顶部和底部填充。@user6827尝试使用ImageView.ScaleType.FIT\u XY
。我看到了问题,我的image.getWidth()
和image.getHeight()
都是1,这是不正确的。如何修复此问题?@user6827您阅读了有关ImageLoader
的内容,并查看它是否为load complete事件公开了侦听器。我不使用它。我重新加载layoutParams的关键是layout.updateViewLayout(图像,参数);谢谢