繁体   English   中英

设置`layout_weight`时如何设置`ImageView`的高度以匹配它的宽度?

[英]How to set `ImageView`'s height to match it's width while `layout_weight` is set?

这里是处理:我有一个GridViewandroid:numColumns="2" GridView中的项目是带有android:layout_weight="1" ImageViews ,因此它们是屏幕宽度的一半。 问题是height属性,它应该等于宽度。 我尝试使用scaleype ,到目前为止没有成功。 如何设置GridView元素的宽度以填充屏幕的一半并将其高度设置为等于其宽度?

您必须以编程方式获取ImageViews宽度,然后设置高度。

但是如果你只是使用img.getWidth() ; 例如。 OnCreate() ,它将返回0因为它尚未绘制。

所以你必须在OnCreate()做这样的事情:

ImageView img = (ImageView) findViewById(R.id.img); 
ViewTreeObserver vto = img.getViewTreeObserver();
         vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
             public boolean onPreDraw() {
                 int x;
                 img.getViewTreeObserver().removeOnPreDrawListener(this);
                 x = img.getMeasuredWidth();
                 img.setLayoutParams(new LinearLayout.LayoutParams(x,x));
                 return true;
             }
         });

这将在绘制后获得Imageview的宽度,并将其高度设置为等于它。

要将ImageView设置为屏幕的一半,您需要将以下内容添加到ImageView的XML中:

<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerInParent="true"
    android:scaleType="fitXY"
    android:adjustViewBounds="true"/>

要将高度设置为等于此宽度,您需要在代码中执行此操作。 GridView适配器的getView方法中,将ImageView高度设置为等于其测量宽度:

int measuredImageWidth = mImageView.getMeasuredWidth();
mImageView.getLayoutParams().height = measuredImageWidth;

希望这可以帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM