Position the text in the center

Asked

Viewed 675 times

-1

I have this Textview: inserir a descrição da imagem aqui

would like the text to be centered vertically and horizontally in relation to the black area, which is the background of Textview itself, which defined the height of 100dp, what I need to do?

2 answers

3


To center the content, just use the attribute gravity or the method setGravity

In XML:

<TextView
   android:id="@+id/myId"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:text="Hello World"
   android:gravity="center" />

In Java

TextView text = findViewById(R.id.myTextView);
text.setGravity(View.Gravity.CENTER);

The difference between android:layout_gravity and android:Gravity, is that in the first, it will position the element, in case the Textview; Different from the second that will position the content of the element.

0

The property will be the layout_gravity, but it will depend on the type of layout which you are using, or will even use directly in the element, e.g. a textView, so it should also be aligned to your layout, with the gravity.

For example, one of the most commonly used is the LinearLayout in orienteering vertical, you need to use reverse alignment, ie, center_horizontal.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center_horizontal"
    android:orientation="vertical"
    tools:context="br.com.seuprojeto.Main">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_horizontal" />

</LinearLayout>

If you want to know more specifically about this property: Android - Gravity

Browser other questions tagged

You are not signed in. Login or sign up in order to post.