I have an extended RelativeLayout which, when programmed for positioning and size using RelativeLayout.LayoutParams should be limited to a specific format. Typically, I would like it to limit itself to 1: 1, so if RelativeLayout.LayoutParams contains a width of 200 and a height of 100, the custom RelativeLayout will limit itself to 100 x 100.
I'm already used to overriding onMeasure() in a regular custom View to achieve similar goals. For example, I created my own SVG image converter, and a custom View that displays an SVG image has an overridden onMeasure() , which ensures that the call to setMeasuredDimension() contains dimensions that (a) match the original dimension specifications, and (b) correspond to the aspect ratio of the original SVG image.
Returning to my custom RelativeLayout , which I want to hide myself in a similar way, I tried to override onMeasure() , but I did not have much success. Knowing that RelativeLayout onMeasure() does all the child layout of View , what I usually try to do at the moment, but without the desired results, is to override onMeasure() , so that I initially change the size specifications first (i.e. apply my desired limitations) and then call super.onMeasure() . Like this:
@Override protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec){ int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec);
What actually happens when I do this is that, oddly enough, the height is limited, as I expected, but there is no width. To illustrate:
Specifying a height of 200 and a width of 100 in RelativeLayout.LayoutParams causes my custom RelativeLayout have a height of 100 and a width of 100. → Fix.
Specifying a height of 100 and a width of 200 in RelativeLayout.LayoutParams causes my custom RelativeLayout have a height of 100 and a width of 200. → Wrong.
I understand that instead, I could apply my aspect ratio restriction logic in the calling class that places the RelativeLayout in the first place (and in the meantime, I can do this to get around this), but actually this is what I want to do RelativeLayout .
Clarification: the resulting width and height values I'm reading are using getWidth() and getHeight() . These values will be read in the future after the build process is completed again.