Set "gravity" attribute to a RelativeLayout not working

 How gravity affects the subviews is shown in the image below.



I resized the widths of all the subviews so that what is happening is more clear. 

Note that the way RelativeLayout handles gravity is to take all the subviews as a group and move them around the layout. This means that whichever view is widest will determine how everything else is positioned. So gravity in a Relative layout is probably only useful if all the subviews have the same width.


Linear Layout with gravity

When you add gravity to a LinearLayout, it does arrange the subviews as one would expect. 

For example, one could "save code" by setting the gravity of LinearLayout to center_horizontally. That way there is no need individually set the layout_gravity of each subview. See the various options in the image below.

enter image description here

Note that when a view uses layout_gravity, it overrides the LinearLayout's gravity. (This can be seen in the title for the two layouts in the left image. The LinearLayout gravity was set to leftand right, but the title TextView's layout_gravity was set to center_horizontally.)

Final notes

When positioning views within a RelativeLayout, the general way to do it is adding things like the following to each view:

  • layout_alignParentTop
  • layout_centerVertical
  • layout_below
  • layout_toRightOf

If one wants to set all the views at once, a LinearLayout would likely be better (or perhaps using a Style).

So to sum up,

  • The layout_gravity does not work for subviews in a RelativeLayout.
  • The gravity of a RelativeLayout does work, but not as one might expect.


From: http://stackoverflow.com/questions/42142058/why-doesnt-gravity-work-when-applied-to-relative-layout/42153928#42153928

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值