Right align text in android TextView

2019-01-08 05:53发布

I have a TextView in my application. I want to align the text in it to the right. I tried adding:

android:gravity="right"

But this doesn't work for me.

What might I be doing wrong?

18条回答
姐就是有狂的资本
2楼-- · 2019-01-08 06:05

Let me explain gravity concept using WEB because a lot of developer are aware of it.

android_layout_gravity behaves float:left|right|top|bottom

Whereas android_gravity work as text_align:centre|left|right

In Android float is android_layout_gravity and text_align: is android_gravity.

And android_layout_gravity applies relative to parent. where as android_gravity applies to its child or inner content.

Note android_gravity only works when its View is match_parent(when it have space to center).

查看更多
太酷不给撩
3楼-- · 2019-01-08 06:06

You can use:

    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"
查看更多
Anthone
4楼-- · 2019-01-08 06:07
android:gravity="right"

It is basically used in Linear Layout so you have to set your width of TextView or either EditText as

android:layout_width = "match_parent"

and

When you are working in Relative Layout, use

android:layout_alignParentRight="true"
查看更多
戒情不戒烟
5楼-- · 2019-01-08 06:10

In my case, I was using Relative Layout for a emptyString

After struggling on this for an hour. Only this worked for me:

android:layout_toRightOf="@id/welcome"
android:layout_toEndOf="@id/welcome"
android:layout_alignBaseline="@id/welcome"

layout_toRightOf or layout_toEndOf both works, but to support it better, I used both.

To make it more clear:

This was what I was trying to do:

enter image description here

And this was the emulator's output

enter image description here

Layout:

<TextView
    android:id="@+id/welcome"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="16dp"
    android:layout_marginTop="16dp"
    android:text="Welcome "
    android:textSize="16sp" />
<TextView
    android:id="@+id/username"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@id/welcome"
    android:layout_toRightOf="@id/welcome"
    android:text="@string/emptyString"
    android:textSize="16sp" />

Notice that:

  1. android:layout_width="wrap_content" works
  2. Gravity is not used
查看更多
Animai°情兽
6楼-- · 2019-01-08 06:11

Make sure that you are not using android:layout_width="wrap_content" if so then it won't be able to set the gravity because you are not having enough space for the text to align. Instead use android:layout_width="fill_parent"

查看更多
神经病院院长
7楼-- · 2019-01-08 06:14

I think that you are doing this: android:layout_width = "wrap_content"
If this is the case, do this: android:layout_width = "match_parent"

查看更多
登录 后发表回答