I have been trying to use layout_gravity
in a horizontal linear layout
. But it doesn't seem to work. I don't want to use a relative layout
or any other layout. I want to know why it is not working with linear layout
.I have earlier used layout_gravity
in vertical
linear layouts and it has worked in the way I expected.
<LinearLayout
android:id="@+id/shata"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<TextView
android:id="@+id/title_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textColor="@color/black"
android:text="shata1"
android:textAppearance="?android:attr/textAppearanceMedium"
/>
<TextView
android:id="@+id/map_imageview"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="right"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="shata2"/>
</LinearLayout>
As you can see the the linear layout has a orientation=horizontal
and width=match_parent
(it is just inside the root layout). But both the TextViews are displayed sticking to the left of the LinearLayout
even though I have given their layout_gravity=center
and layout_gravity=right
respectively.
Short answer: If you have a horizontal LinearLayout, then each child can only have layout_gravity
values of top
, bottom
, and center
.
The reason for this is because you've already told the LinearLayout
to align each child horizontally, left-to-right in the order you specify, which means that it only lets you specify the vertical alignment of each child in the layout_gravity
parameter, and the opposite applies when your LinearLayout
is vertical.
There's a good link explaining how the various gravities work here.