【发布时间】:2019-03-21 18:36:14
【问题描述】:
我的目标是让 2 个 TextViews(textLeft、textRight)彼此相邻。 textLeft 应该与父级的左侧对齐。 textRight 应该始终是textLeft 的直接右侧(而不是设备的最右侧),如果textLeft 太长,则不应将其推出屏幕。
水平LinearLayout 在这里没有用,因为使用权重会固定视图大小,这是不希望的。
我一直在使用这个RelativeLayout,如果textLeft 不太长,它可以正常工作。对于较长的文本,textRight 会被推离屏幕。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".TextAlignActivity">
<TextView
android:id="@+id/textLeft"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="10sp"
android:maxLines="3"
android:ellipsize="end"
android:text="Text On the Left - long random text to follow"
/>
<TextView
android:id="@+id/textRight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="@+id/textLeft"
android:layout_alignParentRight="true"
android:textSize="10sp"
android:maxLines="1"
android:text="Text on the Right"
/>
</RelativeLayout>
我猜 ConstraintLayout 可能很适合这种情况,但我不是很熟悉。如果可能的话,我想避免这种情况,因为它需要对我现有的布局进行大量重写。
编辑:
为了简化我的查询,我在示例中使用了 2 个
TextViews。在我的应用程序代码中,textLeft是一个垂直的LinearLayout,带有 2 个TextViews(textLeftTop和textLeftBottom),而不是单个TextView,如示例所示。我希望适用于 2TextViews的解决方案也适用于LinearLayout和TextView。
1234563如果
textLeft 很长,那么textRight 应该“粘”到设备右侧,textLeft 应该换行。
【问题讨论】:
-
@Wonay 该线程有所帮助,但已接受的答案中缺少的一个关键是固定边距被应用为对右孩子的黑客攻击。在我的问题中,我事先不知道 textRight 的宽度,因此不能在 textRight 上使用固定边距,在 textLeft 上使用等效填充。