sangeetha sangeetha - 5 months ago 15
Android Question

How to center the textview horizontally and vertically in android

How to center the

TextView
horizontally and vertically in android. I tried using
gravity:center
. But text is displayed in the
center vertically
. I want it to be displayed horizontally too. How to do that.

Here is my code:

<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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.display.MainActivity$PlaceholderFragment" >

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/edit_mesaage"
android:hint="@string/edit_message" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/send"
android:id="@+id/send"
android:onClick="displaym"/>
<TextView
android:id="@+id/display_mes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"/>
</LinearLayout>

Answer

Try changing the LinearLayout to a RelativeLayout. Then for your TextView, try

<TextView 
     android:id="@+id/display_mes"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_centerHorizontal="true"
     android:layout_centerVertical="true"/>

This usually works for me.

Comments