Rich S
Rich S

Reputation: 3453

Can't get vertical alignment working on custom ViewGroup

I've have the following class, which extendes the ViewGroup class.

I indicate that I want the text aligned 'BOTTOM | RIGHT' which works fine if the Button is in a LinearLayout, but in my custom derivation, it only takes into account the 'RIGHT' parameter.

I have massively simplified my class to make it easier to read.

Is there something obvious I'm missing?

Thanks Rich

public class LayoutManager extends ViewGroup
{
    private Button b1;
    public LayoutManager(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        LocalInit(context);
    }

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

    public LayoutManager(Context context)
    {
        super(context);
        LocalInit(context);
    }
    private void LocalInit(Context context)
    {
        b1=new Button(context);
        b1.setText("hello button 1");
        b1.setGravity(Gravity.BOTTOM | Gravity.RIGHT);
        super.addView(b1);
    }
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b)
    {
        b1.layout(100, 100, 300, 300);
    }

}

Upvotes: 2

Views: 358

Answers (1)

mmaag
mmaag

Reputation: 1584

You have to use View.measure(int widthMeasureSpec, int heightMeasureSpec) to tell your Button that it will be 200 x 200 regardless of how big it wants to be. Add this to LayoutManager:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    b1.measure(MeasureSpec.makeMeasureSpec(200, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(200, MeasureSpec.EXACTLY));
}

Upvotes: 5

Related Questions