android - 左视图将占用水平 LinearLayout 中的所有空间
问题描述
我有两个 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
。但如果不止一行,tv1将占用所有空间:text
我认为这可能是因为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
宽度,但除了编程还有其他方法吗?
解决方案
最后我设法通过使用padding做到了:
<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="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="12sp"
android:text="HelloWorld"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/tv2"
android:layout_width="12sp"
android:layout_height="wrap_content"
android:text="*"
app:layout_constraintRight_toRightOf="@id/tv1"
app:layout_constraintTop_toTopOf="@id/tv1" />
</androidx.constraintlayout.widget.ConstraintLayout>
重点是使用 tv2 对 tv1 的从右到右约束,并设置 tv2 的固定尺寸宽度和 tv1 的填充右尺寸。所以 tv2 覆盖在 tv1 的顶部(和内部)。
推荐阅读
- flutter - 显示列表中的随机 10 个元素
- haskell - 函数 toEnum 中的非详尽模式
- c# - Xamarin Forms 全局变量更新比代码慢
- c - 线程 VS 进程 (C)
- python - 如何通过行首的字母间隔在Python中浏览csv
- graphql - Apollo 客户端未使用预期的 uri 连接远程 GraphQL 服务器
- linux - 在汇编中编写随机数生成器的奇怪行为
- ffmpeg - 将大量 MP3 文件转换为 YouTube 视频,每个都使用相同的 JPEG 图像
- xamarin - KFGQPC Uthmanic Script HAFS 无法正确塑造 Xamarin 表单中的阿拉伯数字
- r - 在两个字符串中查找匹配对