1

Let's say I have two views that I want to center vertically. The first view is bigger than the second view.

I noticed that if I place theses two views inside a RelativeLayout with properties layout_height="wrap_content" and android:gravity="center_vertical" nothing happens. This is what I get :

enter image description here

In the opposite, if I place these two views inside a LinearLayour with properties layout_height="wrap_content" and android:gravity="center_vertical" the views are centered vertically :

enter image description here

Lastly, if I place these two views inside a RelativeLayout with properties layout_height with a fixed height and android:gravity="center_vertical" I get the same result as the LinearLayout. The views are centered vertically.

I would expect the views to be centered vertically in each case. Do you know the reason for this difference?

Udara Abeythilake
  • 1,215
  • 1
  • 20
  • 31
Esteam
  • 1,911
  • 1
  • 16
  • 24
  • Possible duplicate of [Android relative layout problem with gravity](http://stackoverflow.com/questions/2804411/android-relative-layout-problem-with-gravity) – OneCricketeer Oct 02 '16 at 12:59

3 Answers3

1

LinearLayout handles all its child object based on its orientation (Horizontal or vertical). So when you are saying gravity: "center_vertical". You are actually referencing based on your parent layout.

In case of RelativeLayout,it enables you to specify the location of child objects relative to each other (child A to the left of child B) or to the parent (aligned to the top of the parent).

Personally I would use gravity only in LinearLayouts and the centerInParent for RelativeLayouts.

O_o
  • 1,103
  • 11
  • 36
0

In your first case it'll work with RelativeLayout as you expected if you use android:layout_centerVertical="true" to the child view which you want to be centred.

So in case of LinearLayout you need to specify the orientation first (i.e. horizontal/vertical) so that the child views are inflated based on the reference of your parent layout.

While in RelativeLayout, as the name says it all, you can specify the position with respect to the views which are the child of a parent RelativeLayout.

Now the views you want to achieve can be generated in many other ways too.

For example, set your parent layout as LinearLayout. Don't specify any gravity attribute in the parent layout. Hence, you set a layout_gravity attribute to the child to certer_vertical and this should work too.

Reaz Murshed
  • 23,691
  • 13
  • 78
  • 98
0

Well, after some others tests, it seems that the behavior of android:gravity for a RelativeLayout is a bit random. I will just avoid to use is.

Esteam
  • 1,911
  • 1
  • 16
  • 24