我如何尺寸大小可根据其父布局大小的视图。比如我有一个 RelativeLayout的
填满整个屏幕,我想要个孩子看,说,一个的ImageView
,以占据整个高度,和1/2的宽度?
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?
我试过在 onMeasure
, onLayout
, onSizeChanged ,等等,我无法得到它的工作......
I've tried overriding all on onMeasure
, onLayout
, onSizeChanged
, etc and I couldn't get it to work....
我不知道是否有人还在读此线程与否,但杰夫的解决方案只会让你一半了(有点夸张)。他有什么onMeasure会做的是在半父显示一半的图像。现在的问题是,调用super.onMeasure前 setMeasuredDimension
将衡量所有的孩子在原有基础上尺寸的看法,那么就削减视图一半时, setMeasuredDimension
调整它的大小。
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.
相反,你需要调用 setMeasuredDimension
(按要求的onMeasure覆盖)的和的提供了一个新的的LayoutParams
为您的看法,的然后的通话 super.onMeasure
。记住,你的的LayoutParams
从您的视图的父类派生,而不是你认为的类型。
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);
}
我认为唯一的一次,你就会有问题,父的LayoutParams
是,如果父母是 AbsoluteLayout
(这是pcated德$ P $,但有时仍然会很有用)。
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).