我有一个正在扩展LinearLayout的自定义视图。这个自定义视图包含其他几个视图,它们的布局应该与LinearLayout完全相同,但是,我没有正确布局它们。。。所有子视图叠放在一起,隐藏之前添加的所有子视图。
我的onLayout和onMeasure如下:
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
// Do nothing. Do not call the superclass method--that would start a layout pass
// on this view's children. PieChart lays out its children in onSizeChanged().
super.onLayout(changed, l, t, r, b);
Log.e(LOG_TAG, LOG_TAG + ".onLayout: " + l + ", " + t + ", " + r + ", " + b);
int iChildCount = this.getChildCount();
for ( int i = 0; i < iChildCount; i++ ) {
View pChild = this.getChildAt(i);
pChild.layout(l, t, pChild.getMeasuredWidth(), pChild.getMeasuredHeight());
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// Try for a width based on our minimum
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
Log.d(LOG_TAG, LOG_TAG + ".onMeasure: width: " + widthMeasureSpec + " getWidth: " + MeasureSpec.getSize(widthMeasureSpec));
Log.d(LOG_TAG, LOG_TAG + ".onMeasure: height: " + heightMeasureSpec + " getHeight: " + MeasureSpec.getSize(heightMeasureSpec));
Log.d(LOG_TAG, LOG_TAG + ".onMeasure: getPaddingLeft: " + getPaddingLeft() + " getPaddingRight: " + getPaddingRight());
Log.d(LOG_TAG, LOG_TAG + ".onMeasure: getPaddingTop: " + getPaddingTop() + " getPaddingBottom: " + getPaddingBottom());
// http://stackoverflow.com/a/17545273/474330
int iParentWidth = MeasureSpec.getSize(widthMeasureSpec);
int iParentHeight = MeasureSpec.getSize(heightMeasureSpec);
this.setMeasuredDimension(iParentWidth, iParentHeight);
int iChildCount = this.getChildCount();
for ( int i = 0; i < iChildCount; i++ ) {
View pChild = this.getChildAt(i);
this.measureChild( pChild,
MeasureSpec.makeMeasureSpec(iParentWidth, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(iParentHeight, MeasureSpec.EXACTLY)
);
}
}
如何设置自定义视图的x位置、y位置、宽度和高度?我已经将自定义视图的LayoutParam设置为WRAP_CONTENT,但是,它的行为仍然像FILL_PARENT,占用了父视图中所有可用的空间。我改变位置或大小的所有努力似乎都不起作用(我甚至尝试设置Padding来控制位置)
我为同样的问题挣扎了一段时间。看起来已经很久没有人问了,但以下是我为让它发挥作用所做的。也许这会帮助其他人。
扩展LinearLayout意味着,如果您希望onLayout显示与LinearLayout相同的子视图,则不必覆盖onLayout。我所要做的就是删除onLayout方法,让LinearLayout类来处理它。
layout()
方法的第三个和第四个参数分别是"相对于父对象的右侧位置"one_answers"相对于父节点的底部位置",而不是您认为的宽度和高度。