Android 无法将子项添加到自定义布局(从 ViewGroup 继承)

Android cannot add children to a custom Layout (inherit from ViewGroup)

嗨,我是 android 开发的新手,我正在尝试创建自己的自定义布局:

public class EqLayout extends ViewGroup {

public EqLayout(Context context){
    super(context);
}

public EqLayout(Context context, AttributeSet attrs){
    super(context, attrs);
}

public EqLayout(Context context, AttributeSet attrs, int defstyle){
    super(context, attrs, defstyle);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int lato = getLato();
    int w = getMeasuredWidth()/lato;
    int h = getMeasuredHeight()/lato;
    int ws = MeasureSpec.makeMeasureSpec(w, MeasureSpec.EXACTLY);
    int hs = MeasureSpec.makeMeasureSpec(h, MeasureSpec.EXACTLY);

    for(int i = 0; i < getChildCount(); i++){
        View v = getChildAt(i);
        v.measure(ws, hs);
    }
}

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    int lato = getLato();
    int w = (r - l)/lato;
    int h = (t - b)/lato;

    for(int i = 0; i < getChildCount(); i++){
        View v = getChildAt(i);
        int x = i%lato, y = i/lato;
        v.layout(x*w, y*h, (x+1)*w, (y+1)*h);
    }

}

private int getLato(){
    int r = (int) Math.ceil(Math.sqrt(getChildCount()));
    r = (r > 0) ? r : r+1;
    return r;
    }
  }

主要活动:

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    EqLayout eql = (EqLayout) findViewById(R.id.eqlviewlayout);
    for(int i = 0; i < 14; i++){
        Button b = new Button(this);
        b.setText("#"+i);
        eql.addView(b);
    }
    }
}

那就是 xml:

似乎一切正常,但我无法向其中添加子项。 我通过拖放按钮在运行时和 Android Studio 中尝试,但没有成功。

有人知道为什么会这样吗?感谢您的宝贵时间,询问您是否需要更多信息。

您的 children 身高为负值。

只需在您的 onLayout 中替换这一行:

int h = (t - b)/lato;

int h = (b - t)/lato;

你很好!