android - 一个 Textview 在 ConstraintLayout 中与另一个重叠
问题描述
我有 ConstraintLayout,里面有两个 TextView:
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/first"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/second"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toRightOf="@+id/first"
app:layout_constraintRight_toRightOf="parent"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</androidx.constraintlayout.widget.ConstraintLayout>
我想将第一个放在父容器的左上角,并将第二个放在父容器的右上角。但是两个文本视图都可以包含任意长度的文本。当第一个文本很长时,它会与第二个文本视图重叠。我可以通过在 LinearLayout 中包装两个文本视图来解决这个问题。但这种方式在我看来并不优雅。也许还有另一种方法可以做到这一点?我的意思是 ConstraintLayout 的功能
解决方案
首先,wrap_content
从你的宽度中删除,因为这使得左/右约束无关紧要。在其位置使用0dp
以使其遵守约束规则。
然后在视图之间创建一个水平链并将其设置为spread
,以便视图在任何点都不会重叠,并且它们也始终停留在屏幕的边缘。
最后,相应地对齐文本,使左侧对齐到视图的开头,右侧对齐到末尾。在下面的示例中,您会看到无论文本有多长,视图都不会重叠并粘在它们的两侧。
注意:为了适应具有不同文本方向的设备,使用开始/结束约束(如在我的代码中)而不是左/右被认为是更好的做法。您还可以通过添加适当的边距来修改下面的代码,使文本远离屏幕边缘。
<?xml version="1.0" encoding="utf-8"?>
<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">
<TextView
android:id="@+id/first"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textAlignment="viewStart"
app:layout_constraintEnd_toStartOf="@+id/second"
app:layout_constraintHorizontal_chainStyle="spread"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="@tools:sample/lorem/random" />
<TextView
android:id="@+id/second"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textAlignment="viewEnd"
app:layout_constrainedWidth="true"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_chainStyle="spread"
app:layout_constraintStart_toEndOf="@id/first"
app:layout_constraintTop_toTopOf="parent"
tools:text="@tools:sample/lorem/random" />
</androidx.constraintlayout.widget.ConstraintLayout>
推荐阅读
- multithreading - 在 Rust 命令过程中写入 stdio 并从 stdout 读取
- npm - 如何在不指定新目录的情况下使用 Yarn 2(或 3)运行 create-react-app?
- jmeter - 如何使用 jms 将多个消息发送到队列
- java - addToBackStack 和 popBackStack 不工作
- python - 在小型实践 RDD 上使用 .filter 和 .collect 打印所有以 'h' 开头的单词(pyspark 初学者)
- python - Python API GET 请求根据 JSON 响应中的对象自动生成电子邮件
- java - AndroidStudio - 在进行片段事务时保持布局参数(高度、宽度)
- javascript - Microsoft azure“文本到语音”javascript,onend 事件
- javascript - 递归函数有效,生成版本错误
- javascript - 如何创建删除元素父节点的元素onclick?