如何根据父视图的尺寸调整 Android 视图的大小 [英] How to size an Android view based on its parent's dimensions

查看:17
本文介绍了如何根据父视图的尺寸调整 Android 视图的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何根据父布局的大小调整视图的大小.例如,我有一个 RelativeLayout 填充全屏,我想要一个子视图,比如 ImageView,占据整个高度,宽度的 1/2?

我已经尝试覆盖 onMeasureonLayoutonSizeChanged 等上的所有内容,但我无法让它工作.......

解决方案

我不知道是否有人还在阅读这个帖子,但 Jeff 的解决方案只会让你完成一半(字面意思).他的 onMeasure 将做的是在父级的一半中显示一半的图像.问题是在 setMeasuredDimension 之前调用 super.onMeasure 将根据原始大小测量视图中的所有子项,然后在 setMeasuredDimension 时将视图切成两半调整它的大小.

相反,您需要调用 setMeasuredDimension(根据 onMeasure 覆盖的要求)为您的视图提供一个新的 LayoutParamsthen 调用 super.onMeasure.请记住,您的 LayoutParams 派生自视图的父类型,而不是视图的类型.

@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){int parentWidth = MeasureSpec.getSize(widthMeasureSpec);int parentHeight = MeasureSpec.getSize(heightMeasureSpec);this.setMeasuredDimension(parentWidth/2, parentHeight);this.setLayoutParams(new *ParentLayoutType*.LayoutParams(parentWidth/2,parentHeight));super.onMeasure(widthMeasureSpec, heightMeasureSpec);}

我相信只有当父 LayoutParams 出现问题时,父是 AbsoluteLayout(已弃用,但有时仍然有用).

How can I size a view based on the size of its parent layout. For example I have a RelativeLayout that fills the full screen, and I want a child view, say an ImageView, to take up the whole height, and 1/2 the width?

I've tried overriding all on onMeasure, onLayout, onSizeChanged, etc and I couldn't get it to work....

解决方案

I don't know if anyone is still reading this thread or not, but Jeff's solution will only get you halfway there (kinda literally). What his onMeasure will do is display half the image in half the parent. The problem is that calling super.onMeasure prior to the setMeasuredDimension will measure all the children in the view based on the original size, then just cut the view in half when the setMeasuredDimension resizes it.

Instead, you need to call setMeasuredDimension (as required for an onMeasure override) and provide a new LayoutParams for your view, then call super.onMeasure. Remember, your LayoutParams are derived from your view's parent type, not your view's type.

@Override 
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
   int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
   int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
   this.setMeasuredDimension(parentWidth/2, parentHeight);
   this.setLayoutParams(new *ParentLayoutType*.LayoutParams(parentWidth/2,parentHeight));
   super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

I believe the only time you'll have problems with the parent LayoutParams is if the parent is an AbsoluteLayout (which is deprecated but still sometimes useful).

这篇关于如何根据父视图的尺寸调整 Android 视图的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆