【发布时间】:2021-10-18 06:01:52
【问题描述】:
我有两个 TextView(tv1 和 tv2),我希望 tv2 位于 tv1 的右侧,如下所示:
或
(抱歉,我没有足够的声誉,无法嵌入图片:(
所以我做了这样的布局:
<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="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/tv2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="*" />
</LinearLayout>
如果 tv1 的text 在一行之内,则一切正常。但如果text 不止一行,tv1 将占据所有空间:
我认为可能是因为Android按照它们在布局文件中出现的顺序排列视图,所以我将根视图从LinearLayour更改为ConstraintLayout并首先制作tv2:
<androidx.constraintlayout.widget.ConstraintLayout
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="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="@+id/tv2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="*"
app:layout_constraintLeft_toRightOf="@+id/tv1"
app:layout_constraintStart_toEndOf="@+id/tv1"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
这仍然不起作用。我知道我可以使用setLayoutParams 以编程方式设置tv1 的宽度,但是除了编程还有其他方法吗?
【问题讨论】: