Android align text top center
Asked Answered
H

4

13

I'm sorry if this is a duplicate but i couldn't find anything that was quite what I'm looking for. Basically, i want to align the text in the text View to be in the top center. And I would like to do this in XML if possible. So i want to combine

android:gravity="center"

and

android:gravity="top"

so that it aligns it with both. I have already tried to put both attributes in the text View element but it just gives an error.

Haruspicy answered 10/7, 2014 at 18:45 Comment(1)
Please post the error and all other relevant informationPilocarpine
C
22

First, you cannot duplicate the attribute, though you can combine values.

android:gravity="g1|g2"

However, center implies both vertical and horizontal centering so top|center wouldn't be correct. You should use

android:gravity="top|center_horizontal"
Carbone answered 10/7, 2014 at 18:49 Comment(1)
But when I tried on android studio. Just "top|center" is good, too. Guess they have same effect on TextView implementation.Raymer
C
2

If you want to apply more than one propery to gravity you must use | like this

android:gravity="top|center"
Canicula answered 10/7, 2014 at 18:50 Comment(0)
Z
1

use a RelativeLayout as your ViewGroup and do this:

 <?xml version="1.0" encoding="utf-8" ?>
 <RelativeLayout  xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_height="match_parent"
     android:layout_width="match_parent">
     <TextView
        android:id="@+id/textViewDemo"
        android:layout_alignParentTop="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"/>

  </RelativeLayout>
Zurkow answered 10/7, 2014 at 18:51 Comment(0)
I
0

just add this line to your textview and it will center and top to layout:

android:layout_centerHorizontal="true"
Ideograph answered 15/10, 2022 at 20:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.