更新的LayoutParams不工作(Updating layoutParams not worki

2019-09-01 06:46发布

我试图计算这个形象,这将从网络使用该线路下载尺寸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"
        />  

Answer 1:

该意见还没有敷设在onCreate()方法,因此它们的尺寸都是0张贴RunnableonCreate()来获得正确的价值观:

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

});


Answer 2:

您也可以使用ViewTreeObserver尽快布局完成后得到的值。

参考- 你怎么知道当一个布局已经绘就?



文章来源: Updating layoutParams not working