I have a TextView in a LinearLayout.
I want to try different modes for layout_gravity and gravity.
I have this code:
<LinearLayout
android:layout_width="150dp"
android:layout_height="50dp"
android:background="#A55C93"
android:orientation="horizontal">
<TextView
android:id="@+id/textView1"
android:background="#005Cff"
android:layout_gravity="center"
android:gravity="center"
android:layout_width="50dp"
android:layout_height="25dp"
android:text="text"
android:textSize="21sp" />
</LinearLayout>
When I have android:orientation="vertical", everything about layout_gravity and gravity makes sense. But when I have android:orientation="horizontal", outputs are different from the first, why?
The main thing to understand is that
layout_gravityon a child view is an attribute that communicates "up" to the parent, and "asks" the parent to behave in a certain way.In this case, the parent is a
LinearLayout, which has a different attribute (orientation) that already affects the positioning of child views. Therefore, when a child specifieslayout_gravity, what happens depends on theLinearLayout'sorientation.horizontalLinearLayout, any horizontal component of the child'slayout_gravityis ignored.verticalLinearLayout, any vertical component of the child'slayout_gravityis ignored.You're using
center, which is basicallycenter_vertical+center_horizontal. So for a horizontal LinearLayout, the horizontal centering will be ignored. And, for a vertical LinearLayout, the vertical centering will be ignored.Given that your example only has one child view, you could consider replacing the parent
LinearLayoutwith aFrameLayout. Then the childlayout_gravitywill be fully respected.