I have two views, lets say A and B. I want A to be placed above B vertically, but center-aligned with B horizontaly, i.e. I want to achieve this:
I tried:
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)
viewA.getLayoutParams();
layoutParams.addRule(
RelativeLayout.ABOVE,
viewB.getId()
);
But apparently what it did is placing A vertically above B, but horizontally floating to the left (aligned with X's left)
Please help.
What you have is on the right path, but you need to also add a rule for the horizontal centering:
layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
I recognize that this doesn't quite do what you asked in that it is specifying that you center in the parent view horizontally as opposed to specifying that you align the horizontal centers of A and B, but there isn't a direct way to do the latter with a RelativeLayout rule. (There are many indirect ways to do it instead.)
Addition:
Given that your view
A
is not centered horizontally in the parent, here's a suggestion. I don't know of a great / non-hacky way to do this, but I think that since RelativeLayout rules are applied during the measurement pass, you can use the left (and right) coordinates of viewA
after measurement is done to set the (public)left
andright
properties of viewB
to what they need to be in order to center the view underA
.So for example, if your parent view is a custom extension of View you can override its
onMeasure()
method, call like:And if not, you can use
setOnLayoutChangeListener()
on the parent and a callback to achieve the same thing.