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

时间:2016-06-11 23:30:00

标签: android layout view children 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;
    }
  }

MainActivity:

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:

XML file

一切似乎都运转良好,但我无法添加一个孩子。 我在运行时尝试并通过拖放按钮从Android Studio但没有成功。

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

1 个答案:

答案 0 :(得分:1)

您的孩子身高不足。

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

int h = (t - b)/lato;

int h = (b - t)/lato;

你很好!

Screenshot