我正在尝试将项目动态添加到我的 CustomView 并使最终高度成为添加在一起的所有子项的大小。唯一的问题是 child.getMeasuredHeight 或 child.getMeasuredWidth 在运行时总是返回值 0。当我调试时,它会随机 10 次中的 1 次似乎实际上包含我实际期望的值为 192 的数据。如果我还将一个值硬编码到布局参数中而不是使用 WRAP_CONTENT 它仍然显示一个值0.我做错了什么。
xml文件
<CustomLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_marginTop="80dp"
android:orientation="vertical"
android:layout_width="200dp"
android:layout_height="100dp"
android:id="@+id/custom_layout"
android:background="@drawable/custom_shape"/>
</CustomLayout>
这是我的 CustomLayout.java 类的一部分
public class CustomLayout extends LinearLayout {
public CustomLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomLayout(Context context) {
super(context);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int count = getChildCount();
int maxHeight = 0;
int maxWidth = 0;
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
for(int i=0; i <count; i++) {
final View child = getChildAt(i);
if(child.getVisibility() != GONE) {
maxHeight += child.getMeasuredHeight();
}
}
setMeasuredDimension(widthSize,maxHeight);
}
在我的主要活动的一部分
Button b = new Button(this);
b.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
b.setText("Sample Test");
b.setTextSize(14);
mCustomView.addView(b);