Place the text in the center

-1

I have this TextView:

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

    
asked by anonymous 20.12.2017 / 00:11

2 answers

3

To centralize content, simply use the gravity attribute or the setGravity

No 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 this case TextView ; Different from the second that will position the content of the element.

    
20.12.2017 / 00:25
0

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

For example, one of the most commonly used LinearLayout in the vertical orientation, you need to use the inverse alignment, that is, 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 about this property: Android - Gravity

    
20.12.2017 / 11:09