2

I have two TextViews next to each other inside ConstraintLayout. Each of them has two words. The words inside of them can be changed by the current locale.

Currently each of them takes equally space on the width by using android:layout_weight="1" and android:layout_width="0dp"

If the text in any of them is too long to fit one line, I want both of them to expand to two lines. I need the text itself to be expanded, not the TextView - that can be done only if the text has at least two words.

Is there a way to do that?

expected behaviour

Cheticamp
  • 61,413
  • 10
  • 78
  • 131
Smeagol
  • 593
  • 9
  • 23
  • https://stackoverflow.com/questions/6674578/multiline-textview-in-android – Kirguduck Mar 16 '20 at 14:19
  • Does this answer your question? [ConstraintLayout: set height of all views in row to match the tallest one](https://stackoverflow.com/questions/43288173/constraintlayout-set-height-of-all-views-in-row-to-match-the-tallest-one) – Raimo Mar 16 '20 at 14:21
  • @Raimo Actually not, I need to split it to two lines if possible. – Smeagol Mar 17 '20 at 10:42
  • In your example, "Second not" can fit on the one line. Are you saying that the text must occupy two lines if the first does or that the _TextView_ itself must expand to two lines while the second line can be blank? Those are two separate, but related, problems. – Cheticamp Mar 18 '20 at 02:08
  • @Cheticamp the text, I will try to edit to be more clear. – Smeagol Mar 18 '20 at 12:16

1 Answers1

1

You will need for layout to proceed then determine if the left TextView has two lines and, if it does, adjust the right TextView to also occupy two lines. The following code is one way to do this. You can place this in 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")
    }
}
Cheticamp
  • 61,413
  • 10
  • 78
  • 131