Search code examples
androidandroid-layoutandroid-relativelayoutandroid-custom-view

Align bottom for a custom RelativeLayout


Lets say that I have a custom RelativeLayout which override onMeasure :

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    setMeasuredDimension(200, 200);
}

Now I'd like to add to this Layout a View which align with the bottom of this Custom RelativeLayout. But I tried different things without any results :

paramsButton.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
addView (mButton, paramsButton);

My first guess was to align bottom with parent (which should be the custom RelativeLayout right ?). But apparently, it aligns with the parent of my custom Layout (which is another RelativeLayout, not custom this time.

So I tried to align with id :

paramsButton.addRule(RelativeLayout.ALIGN_BOTTOM, getId());
addView (mButton, paramsButton);

but it's not working either (the button disappears) NB : I set the id of my custom RelativeLayout explicitly to check that android did get the right id.

Do you have any idea how to make this work ?

EDIT : Funny thing : It work well with the following rule

paramsButton.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
addView (mButton, paramsButton);

So I have to say that i really don't understand why the

RelativeLayout.ALIGN_PARENT_BOTTOM

rule is not working...


Solution

  • Your approach to overriding onMeasure is flawed. In this case, the layout measures its children (and they store their size) and then you tell just the layout (and not the children) that you actually changed your mind and would like to change that size.

    Instead, try the following:

    widthMeasureSpec = MeasureSpec.makeMeasureSpec(200, MeasureSpec.EXACTLY);
    heightMeasureSpec = MeasureSpec.makeMeasureSpec(200, MeasureSpec.EXACTLY);
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    

    In general, putting size in the code is not a great idea. Instead, consider using a style with fixed-size layout_width and layout_height or at the very least using <dimen> resources.