我有两个自定义viewgroups
,superViewGroup
和subViewGroup
。子视图组包含视图。我将我的superviewgroup添加到linearLayout,将subViewGroups
添加到我的superviewgroup
。
superviewgroup onMeasure()
正在调用但不在子视图组中。但是在这两种情况下都会调用onLayout()
方法。
代码如下
public class SuperViewGroup extends ViewGroup{
public SuperViewGroup(Context context) {
super(context);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
Log.i("boxchart","INSIDE ON MEASURE SUPER VIEWGROUP");
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final int count = getChildCount();
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() != View.GONE) {
child.layout(0, 0, getWidth(), getHeight());
}
}
}
}
public class SubViewGroup extends ViewGroup{
public SubViewGroup(Context context) {
super(context);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
Log.i("boxchart","INSIDE ON MEASURE SUB VIEWGROUP");
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final int count = getChildCount();
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() != View.GONE) {
child.layout(0, 0, getWidth(), getHeight());
}
}
}
}
评论表示赞赏。提前谢谢。
答案 0 :(得分:7)
因为您必须将度量实际传递给子视图:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
Log.i("boxchart","INSIDE ON MEASURE SUPER VIEWGROUP");
final int count = getChildCount();
final int count = getChildCount();
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() != View.GONE) {
//Make or work out measurements for children here (MeasureSpec.make...)
measureChild (child, widthMeasureSpec, heightMeasureSpec)
}
}
}
否则你实际上从未测量过你的孩子。由您来决定如何做到这一点。仅仅因为SuperViewGroup
处于线性布局,您的SuperViewGroup
才有责任衡量其子女。