我有一个扩展 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,占用了父视图中的所有可用空间。似乎我所有改变位置或大小的努力都没有奏效(我什至尝试 setPadding 来尝试控制位置)