更新layoutParams不起作用

时间:2013-04-27 12:58:06

标签: android android-imageview

我正在尝试计算此图片的尺寸,该图片将使用此行imgLoader.DisplayImage(url, R.drawable.thumbnail_background, image);从网上下载。 问题是orgHeight变为零,你不能除以零。但为什么这个orgHeight 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"
        />  

2 个答案:

答案 0 :(得分:9)

onCreate()方法尚未显示视图,因此其尺寸为0.从Runnable发布onCreate()以获取正确的值:

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

});

答案 1 :(得分:2)

您也可以使用ViewTreeObserver在布局完成后立即获取值。

参考 - How can you tell when a layout has been drawn?