Center TextView

2

I wanted to know how to center a textview, since the title of the app is outdated to the right and not in the center of the screen,  Thank you.

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/TituloApp"
    android:text="HOLA'"
    android:paddingLeft="50dp"
    android:textSize="55dp"
    android:layout_marginTop="30dp"


    />
    
asked by Nicolas Schmidt 05.04.2016 в 17:14
source

4 answers

1

You can use android:layout_centerHorizontal="true" with a layout_width of wrap_content and delete the android:paddingLeft="50dp"

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:id="@+id/TituloApp"
    android:text="HOLA'"
    android:textSize="55dp"
    android:layout_marginTop="30dp" />
    
answered by 05.04.2016 / 17:45
source
4

It can be programmatically:

textView.setGravity(Gravity.CENTER);

or by changing the property directly in the layout:

   <TextView  
        android:layout_width="match_parent" 
        android:layout_height="match_parent" 
        android:gravity="center"
        android:text="Android"/>

  • You can remove android:paddingLeft="50dp" already pushing your view to the right.
  • I suggest you change layout_width="match_parent" by layout_width="wrap_content" , since "match_parent" is occupying the full width of the parent view.

If you want to center your view but on the whole screen horizontally and vertically, you can do it with a RelativeLayout and use the properties

 android:layout_centerVertical="true"
 android:layout_centerHorizontal="true" 

Example:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/TituloApp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Android"
        android:textSize="55dp"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

    
answered by 05.04.2016 в 17:52
1

Go to the layout where the (Edittext) component is, in XML you put this code to the (android:textAlignment="center") component and then in the java activity you put the component (tv_bienvenida.setGravity(Gravity.CENTER);)

---------Component XML----------
android:textAlignment="center"

-------java-----------------------
tv_bienvenida.setGravity(Gravity.CENTER);
    
answered by 27.09.2018 в 22:28
0

With this:

android:gravity="center" 

From code there are two forms, although both are valid:

textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);

or

textview.setGravity(Gravity.CENTER)
    
answered by 05.04.2016 в 17:39