¿Cómo centro texto horizontal y verticalmente en una vista de texto?
¿Cómo centro el texto horizontal y verticalmente en un TextView
, para que aparezca exactamente en el medio del TextView
en Android
?
30 answers
Asumo que estás usando el diseño XML.
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="@string/**yourtextstring**"
/>
También puedes usar gravity center_vertical
o center_horizontal
según tus necesidades.
Y como @ stealthcopter comentó
en java: .setGravity(Gravity.CENTER);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-10 16:11:32
android:gravity="center"
Esto hará el truco
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-22 14:27:07
También puedes configurarlo dinámicamente usando:
textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-11-21 12:25:56
android:layout_centerInParent="true"
Esto funciona cuando se usa con un RelativeLayout donde la altura y anchura del diseño se establecen en wrap_content.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-11-11 03:33:26
También puedes usar la combinación:
android:gravity="left|center"
Entonces, si el ancho de textview es más que "fill_parent", el texto seguirá alineado a la izquierda (no centrado como con gravity establecido solo en "center").
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-26 08:36:05
Aplicar gravedad:
TextView txtView = (TextView) findViewById(R.id.txtView);
txtView.setGravity(Gravity.CENTER_HORIZONTAL);
Para vertical:
txtView.setGravity(Gravity.CENTER_VERTICAL);
En XML:
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:text="@string/Hello_World"
/>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-17 11:10:19
Si está utilizando TableLayout, asegúrese de establecer la gravedad de las tablas también en el centro. De lo contrario no funcionará. Al menos no funcionó conmigo hasta que puse la gravedad de la tabla en el centro.
Por ejemplo, así:
<TableRow android:id="@+id/tableRow2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center">
<TextView android:text="@string/chf" android:id="@+id/tv_chf" android:layout_weight="2" android:layout_height="wrap_content" android:layout_width="fill_parent" android:gravity="center"></TextView>
</TableRow>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-13 04:49:09
Debe establecer TextView Gravity (Centrar Horizontal y Centrar Vertical) de la siguiente manera:
android:layout_centerHorizontal="true"
Y
android:layout_centerVertical="true"
Y dinámicamente usando:
textview.setGravity(Gravity.CENTER);
textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-13 04:49:52
Hay dos maneras de hacer esto.
El primero en el código XML. Debes prestar atención al atributo Gravity
. También puede encontrar este atributo en el Editor Gráfico; puede ser más fácil que el EDITOR XML.
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical|center_horizontal"
android:text="Your Text"
/>
Para su escenario específico, los valores de gravedad serán:
center_vertical|center_horizontal
En el editor gráfico encontrará todos los valores posibles, incluso ver sus resultados.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-27 13:01:40
En mi opinión,
android:gravity="center"
Es mejor que,
android:layout_centerInParent="true"
Que es mejor Que,
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
Al menos para dar formato al texto.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-12 04:40:21
Para El Diseño Lineal: En XML use algo como esto
<TextView
android:id="@+id/textView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical|center_horizontal"
android:text="Your Text goes here"
/>
Para hacer esto en tiempo de ejecución use algo como esto en su actividad
TextView textView1 =(TextView)findViewById(R.id.texView1);
textView1.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
Para el Diseño Relativo: en XML use algo como esto
<TextView
android:id="@+id/textView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerInParent="true"
android:text="Your Text goes here"
/>
Para hacer esto en tiempo de ejecución use algo como esto en su actividad
TextView textView1 =(TextView)findViewById(R.id.texView1);
RelativeLayout.LayoutParams layoutParams = RelativeLayout.LayoutParams)textView1.getLayoutParams();
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
textView1.setLayoutParams(layoutParams);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-19 06:33:00
Utilizar en el archivo XML.
Archivo de Diseño
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:text="@string/stringtext"/>
O:
Usa esto dentro de la clase Java
TextView textView =(TextView)findViewById(R.id.texviewid);
textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-13 04:57:25
Use esto para el diseño relativo
android:layout_centerInParent="true"
Y para otro diseño
android:gravity="center"
Mientras se usa gravity works para TextView, hay un método alternativo implementado en el nivel de API 17 -
textView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
No conozco la diferencia, pero también funciona. Sin embargo, solo para el nivel de API 17 o superior.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-24 20:50:50
En RelativeLayout
, será bueno con él.
Y otro Button
y cualquier otra cosa que pueda agregar.
Lo siguiente funciona muy bien para mí.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ff314859"
android:paddingLeft="16dp"
android:paddingRight="16dp">
<TextView
android:id="@+id/txt_logo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="your text here"
android:textSize="30dp"
android:gravity="center"/>
...other button or anything else...
</RelativeLayout>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-20 15:43:03
Si el TextView's
alto y ancho son wrap content
entonces el texto dentro del TextView
siempre estará centrado. Pero si el TextView's
ancho es match_parent
y la altura es match_parent
o wrap_content
entonces tienes que escribir el siguiente código:
For RelativeLayout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Hello World" />
</RelativeLayout>
Para LinearLayout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Hello World" />
</LinearLayout>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-12 15:15:59
La forma más fácil (que sorprendentemente solo se menciona en los comentarios, por lo tanto, por qué estoy publicando como respuesta) es:
textview.setGravity(Gravity.CENTER)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-15 12:38:02
Simplemente puede establecer el gravity
de su textview en CENTER
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-27 13:02:15
Si está tratando de centrar el texto en una TableRow en una TableLayout, así es como logré esto:
<TableRow android:id="@+id/rowName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dip" >
<TextView android:id="@+id/lblSomeLabel"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:layout_width="0dp"
android:layout_weight="100"
android:text="Your Text Here" />
</TableRow>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-15 02:14:08
Aquí está mi respuesta que había utilizado en mi aplicación. Muestra texto en el centro de la pantalla.
<TextView
android:id="@+id/txtSubject"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/subject"
android:layout_margin="10dp"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceLarge" />
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-13 04:56:27
Si está utilizando Diseño relativo:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/stringname"
android:layout_centerInParent="true"/>
Si está utilizando LinearLayout
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/stringname"
android:layout_gravity="center"/>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-15 06:33:26
Como sugieren muchas respuestas anteriores funciona bien.
android:gravity="center"
Si quieres centrarlo solo verticalmente:
android:gravity="center_vertical"
O simplemente horizontalmente:
android:gravity="center_horizontal"
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-04 20:09:04
Simplemente, en su archivo XML, establezca la gravedad textview en centro:
<TextView
android:gravity="center" />
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-13 04:54:11
La altura y el ancho de TextView son contenido de ajuste, luego el texto dentro de textview siempre se centra, luego se centra en su diseño padre usando:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Hello.."/>
</RelativeLayout>
Para LinearLayout también el código es el mismo:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello.."/>
</LinearLayout>
Y pro-gramatically padre es RelativeLayout código java esto en tiempo de ejecución utilice algo como esto en su actividad
TextView textView1 =(TextView)findViewById(R.id.texView1);
RelativeLayout.LayoutParams layoutParams = RelativeLayout.LayoutParams)textView1.getLayoutParams();
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
textView1.setLayoutParams(layoutParams);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-07 13:42:51
Puede hacer esto para obtener el texto centrado
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center" />
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-30 09:27:32
Podemos lograr esto con estas múltiples maneras: -
Método XML 01
<TextView
android:id="@+id/textView"
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:gravity="center_vertical|center_horizontal"
android:text="@strings/text"
/>
Método XML 02
<TextView
android:id="@+id/textView"
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@strings/text"
/>
Método XML 03
<TextView
android:id="@+id/textView"
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:gravity="center"
android:text="@strings/text"
/>
Método XML 04
<TextView
android:id="@+id/textView"
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:layout_centerInParent="true"
android:text="@strings/text"
/>
Método Java 01
textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
Método Java 02
textview.setGravity(Gravity.CENTER);
Método Java 03
textView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-14 10:32:20
android:gravity="center_horizontal"
para alinear el centro de texto horizontalmente.
android:gravity="center_vertical"
para alinear el centro de texto verticalmente.
android:gravity="center"
para alinear el centro de texto tanto vertical como horizontalmente.
<TextView
android:layout_width="match_parent"
android:gravity="center_horizontal|center_vertical"
android:layout_height="match_parent" />
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-20 10:18:11
Intente de esta manera, funcionará
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center_horizontal|center_vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAlignment="center" />
</LinearLayout>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-28 07:03:10
Use el siguiente código en xml funcionó para mí puede cambiar la orientación que estará en el centro
<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal"
android:background="@color/colorPrimaryDark"
android:gravity="center"
android:layout_height="wrap_content">
<TextView
android:id="@+id/id_text"
android:layout_width="wrap_content"
android:textSize="18sp"
android:textColor="@android:color/white"
android:textStyle="normal"
android:layout_height="wrap_content"
android:text="centre me"/>
</LinearLayout>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-07 10:26:56
TextView gravity funciona según su diseño padre.
LinearLayout :
Si usa LinearLayout, encontrará dos atributos de gravedad android: gravity & android:layout_gravity
Android: gravity: representar poción de diseño del texto interno de TextView mientras android: layout_gravity: representa la posición de TextView en la vista principal.
Si desea ajustar el texto horizontal y verticalmente al centro, utilice el código siguiente esto
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="300dp"
android:background="@android:color/background_light"
android:layout_height="300dp">
<TextView
android:layout_width="match_parent"
android:text="Hello World!"
android:gravity="center_horizontal"
android:layout_gravity="center_vertical"
android:layout_height="wrap_content"
/>
</LinearLayout>
RelativeLayout :
Usando RelativeLayout puedes usar la siguiente propiedad en TextView
Android:gravity="center" para el centro de texto en TextView.
Android:gravity="center_horizontal" texto interno si quieres centrado horizontalmente.
Android:gravity="center_vertical" texto interno si quieres centrado verticalmente.
Android: layout_centerInParent= "true" si desea TextView en la posición central del padre vista. android: layout_centerHorizontal = "true" si desea TextView en el centro horizontal de la vista principal. android: layout_centerVertical= "true" si quieres TextView en el centro vertical de la vista principal.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="300dp"
android:background="@android:color/background_light"
android:layout_height="300dp">
<TextView
android:layout_width="match_parent"
android:text="Hello World!"
android:gravity="center"
android:layout_centerInParent="true"
android:layout_height="wrap_content"
/>
</RelativeLayout>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-27 13:08:01