您的位置:首页 > 其它

Set "gravity" attribute to a RelativeLayout not working

2017-03-07 18:28 531 查看
 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
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.





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 
left
and 
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐