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

發佈了107 篇原創文章 · 獲贊 87 · 訪問量 58萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章