How to use the center of a View as a reference point inside a RelativeLayout

I like your present solution, but if you want to avoid the funky invisible thin centering widget, you can accomplish that as follows:

  • Calculate containerWidth as the pixel width of your containing RelativeLayout-derived class (call this MyRelativeLayout)
  • Create an instance of MyRelativeLayout.LayoutParams called leftHalfWidgetLayoutParams
  • Set leftHalfWidgetLayoutParams.width = containerWidth / 2, either using the constructor argument when it is created above, or after the fact. After the fact is necessary if you want to adjust it later (e.g., in an override of onSizeChanged() in MyRelativeLayout).
  • Each time you set or change leftHalfWidgetLayoutParams.width, invoke leftHalfWidget.setLayoutParams(leftHalfWidgetLayoutParams).
  • Call requestLayout() if required to redraw MyRelativeLayout each time the width changes

If the widgets to the right of center are overly large, it might be necessary to set their layout width values explicitly, too, to stop them from encroaching into the left half of the container.

Now I realize that this loses some of the "magic" of having RelativeLayout do everything automatically, and that's where your approach is actually nicer. But RelativeLayout is still going to enforce the relative positions of your widgets as well as it can, given the added constraint of the width that will have been added to the layout parameters of your leftHalfWidget, so you wouldn't be overriding or abandoning its overall contribution in that regard.

I can't think of a way to meet your requirements inside a RelativeLayout without explicitly setting the width value on the layout parameters in the manner described above. It's an alternative approach to yours, but not necessarily a better one.

I would point out that if your left-half widget is always going to take up the left half of the container, then I can't see why a horizontal LinearLayout (instead of a RelativeLayout) at the top level (with a weight of 0.5 for your left-size widget with an equally-weighted right side RelativeLayout for the remaining right half), would not be a good solution. The "relative" stuff would, in that case, only be going on within that right half anyway, so why use RelativeLayout at the top level when LinearLayout could do the job more concisely? But perhaps you want to use RelativeLayout on the left side to deal with vertical relationships, and you therefore might actually have more than one control within that left side.


To achieve what you are doing, I use a LinearLayout, layout_width=0dip and layout_weight=50. But it is not optimal as it nests another layout inside the linear layout. I'd be curious to see if another better solution is available.