Levenlol
Levenlol

Reputation: 415

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

hi I'm pretty new to android developing and I'm trying to create my own custom layout:

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);
    }
    }
}

and that's the xml:

XML file

All seems to works fine but I cannot add a child to it. I tried on runtime and from Android Studio by drag and drop a button but without success.

Anybody knows why that happens ? Thanks for you time, ask if you need any more info.

Upvotes: 3

Views: 415

Answers (1)

Enrichman
Enrichman

Reputation: 11337

You have a negative height for your children.

Just replace in your onLayout this line:

int h = (t - b)/lato;

with

int h = (b - t)/lato;

and you're good!

Screenshot

Upvotes: 1

Related Questions