Android - Center Textview in LinearLayout
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.
Try to change your gravity
to
android:layout_gravity="center_vertical"
gravity
is used to position the content inside your View
and layout_gravity
is used to position the View
within its parent.
But I'm confused by "In the end I would like it to be centered vertically to the left of the Linearlayout". But from the way it sounds, my answer should give you what you want.
Also, unless there is a very good reason, you shouldn't need to use a LinearLayout
, or any parent, for a single child. If you can give a better explanation of what you want or even a screenshot then we may be able to help with a better solution.
This will give you your desired effect
<LinearLayout android:layout_width="320dp" <!-- removed orientation (horizontal by default) --> 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:layout_gravity="center_vertical" <!-- changed gravity here --> android:layout_width="fill_parent" android:layout_height="wrap_content" <!-- change to wrap_content --> android:id="@+id/tvExVin" /></LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center_horizontal|center_vertical" android:gravity="center_vertical|center_horizontal" android:orientation="vertical" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="AppLock Demo" android:textSize="30dp" /></LinearLayout>