I am trying to center a TextView
in a LinearLayout
and it is centering horizontaly but not vertically.
below is my code
<LinearLayout
android:orientation="vertical"
android:layout_width="320dp"
android:layout_height="50dp"
android:background="@drawable/rectblack"
android:layout_marginTop="10dp"
android:layout_gravity="center"
android:minWidth="25px"
android:minHeight="25px">
<TextView
android:text="Explode a Vin"
android:gravity="center"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/tvExVin" />
</LinearLayout>
In the end I would like it to be centered vertically to the left of the Linearlayout
, if someone could figure out how to do that, that would be great.
Thanks!
To center align LinearLayout, assign android:gravity attribute of this LinearLayout with the value “center”. Let us create an Android application with LinearLayout containing two Button widgets as children. We shall center align these children using gravity attribute.
If in linearlayout your orientation vertical, you can put the textview in the "horizontal center" by android:layout_gravity="center" . For centering textview vertically you need to set layout_height of textview to match_parent and set android:gravity to "center".
android:gravity="center" for text center in TextView. android:gravity="center_horizontal" inner text if you want horizontally centered. android:gravity="center_vertical" inner text if you want vertically centered. android:layout_centerInParent="true" if you want TextView in center position of parent view.
android:gravity controls the appearance within the TextView. So if you had two lines of text they would be centered within the bounds of the TextView. Try android:layout_centerHorizontal="true" . Notice that this won't work if a RelativeLayout contains an attribute android:gravity="center_horizontal".
You have the gravity and layout_gravity reversed. You can have multiple values on the gravity attribute separated by "|". Try this:
<LinearLayout
android:orientation="vertical"
android:layout_width="320dp"
android:layout_height="50dp"
android:background="@drawable/rectblack"
android:layout_marginTop="10dp"
android:layout_gravity="center_horizontal"
android:gravity="center_vertical|left"
android:minWidth="25px"
android:minHeight="25px">
<TextView
android:text="Explode a Vin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tvExVin" />
</LinearLayout>
For clarification:
android:layout_gravity="center_horizontal"
will center the LinearLayout horizontally in its parent.
android:gravity="center_vertical|left"
will center the TextView (and any other children) vertically inside the LinearLayout and align it to the left.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With