【问题标题】:How to expand second TextView if the first is too long in ConstraintLayout如果第一个在 ConstraintLayout 中太长,如何扩展第二个 TextView
【发布时间】:2020-06-27 15:48:07
【问题描述】:

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

目前,它们中的每一个都使用 android:layout_weight="1" 和 android:layout_width="0dp" 在宽度上占据相等的空间

如果其中任何一个文本太长而无法容纳一行,我希望它们都扩展为两行。我需要扩展文本本身,而不是 TextView - 那只有当文本至少有两个单词时才能完成。

有没有办法做到这一点?

【问题讨论】:

标签: android user-interface textview android-constraintlayout


【解决方案1】:

您需要进行布局,然后确定左侧 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")
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-23
    • 2015-03-16
    相关资源
    最近更新 更多