如果第一个 TextView 在 ConstraintLayout 中太长,如何扩展第二个 TextView

How to expand second TextView if the first is too long in ConstraintLayout

我在 ConstraintLayout 中有两个并排的 TextView。他们每个人都有两个字。 它们里面的词可以被当前的语言环境改变。

目前,通过使用 android:layout_weight="1" 和 android:layout_width="0dp"

,它们中的每一个在宽度上均等 space

如果其中任何一个中的文本太长,一行都放不下,我希望它们都扩展为两行。我需要扩展文本本身,不是 TextView - 只有当文本至少有两个词时才能做到这一点。

有办法吗?

您需要进行布局,然后确定左侧 TextView 是否有两行,如果有,则调整右侧 TextView 也占据两行。以下代码是执行此操作的一种方法。您可以将它放在 onCreate().

val layout = findViewById<ConstraintLayout>(R.id.layout)
layout.doOnNextLayout {
    val textView1 = findViewById<TextView>(R.id.textView1) // Left view
    val textView2 = findViewById<TextView>(R.id.textView2) // Right view
    if (textView1.lineCount == 2) { // If left view has 2 lines, add newline to the right view.
        textView2.text = textView2.text.toString().replace(" ", "\n")
    }
}