我在我的应用程序中有一个TextView
。我想要将其中的文本向右对齐。我尝试添加以下内容:
android:gravity="right"
但这对我不起作用。
我可能做错什么了?
我认为你正在做这个:android:layout_width = "wrap_content"
如果是这样,请改成:android:layout_width = "match_parent"
android:gravity="right"
一般与android:layout_gravity="right"
不同。
第一个属性会影响视图中文本自身的位置,若需要右对齐,则layout_width=
应该为"fill_parent"
或"match_parent"
。
第二个属性则会影响视图在其父视图中的位置,换句话说,是将对象(编辑框或文本视图)在父视图中对齐。
更好的解决方案是最简单的方案,并且对你的代码行为做出的修改最少。
如果您只能在 TextView
上使用 2 个属性就能解决这个问题呢?
与其需要更改可能会改变 LinearLayout
子元素行为的 LinearLayout
属性,不如使用这种方法。
通过这种方式,您无需更改 LinearLayout
的属性和行为,只需将以下两个属性添加到目标 TextView
中:
android:gravity="right"
android:textAlignment="gravity"
将目标仅限于解决问题而不是修改目标本身,这样未来就不会出现新的问题。好好想想吧 :)
如果还有人需要的话
android:gravity="end"
android:layout_gravity
用于将文本视图与父布局对齐。
android:gravity
用于将文本视图中的文本对齐。
您确定要将文本视图中的文本向右对齐,还是想要将文本视图本身与父布局向右移动,或者两者都想实现?
android:textAlignment="textEnd"
android:layout_gravity="end"
对我来说运作得很好
android:gravity="right"
这基本上用于线性布局,所以您需要将TextView或EditText的宽度设置为
android:layout_width = "match_parent"
当您在相对布局中工作时,请使用
android:layout_alignParentRight="true"
请确保您没有使用 android:layout_width="wrap_content"
,否则无法设置重力,因为您没有足够的空间来对齐文本。取而代之,请使用 android:layout_width="fill_parent"
以下方法适用于我:
<TextView
android:id="@+id/tv_username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sarah" />
<TextView
android:id="@+id/tv_distance"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/tv_username"
android:layout_alignParentEnd="true"
android:layout_toEndOf="@+id/tv_username"
android:text="San Marco"
android:textAlignment="viewEnd" />
android:layout_alignParentEnd
和android:textAlignment
设置。