1

I am trying to draw multiline text with StaticLayout but the setMaxLines() does not seem to work. This is my code:

val eventText = StaticLayout.Builder
    .obtain(event.title, 0, event.title.length, eventTextPaint, (contentWidth / 7f).toInt())
    .setMaxLines(2)
    .build()
withTranslation(event.left, event.top * scale) {
    eventText.draw(this)
}

But the all of the text is drawn which is 5 lines long. If I add setEllipsize(TextUtils.TruncateAt.END) I get two lines which is specified in code but with "..." at end, which I do not want. What am I doing wrong? Or is the Builder broken?

enter image description here

OscarCreator
  • 374
  • 4
  • 13

1 Answers1

1

Setting the maximum number a lines doesn't truncate the text within the StaticLayout, but specifies to other code, such as TextView, how many lines are to be displayed.

For example, using the following TextView definition

<TextView
    android:id="@+id/textView"
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:maxLines="2"
    android:text="This is some long text that spans more than two lines. This is some long text that spans more than two lines. This is some long text that spans more than two lines"/>

and setting a breakpoint here in the TextView code we see the following at the breakpoint. In the onDraw() method of TextView, a clip rectangle is defined that has its bottom set to the bottom of line 1 (the second line). It is this code that restricts the number of lines to be displayed. The text in the layout is the long text but only two lines are displayed.

enter image description here

What is displayed:

enter image description here

You will need to do something similar to limit the number of lines displayed, or you can examine the StaticLayout and truncate the number of characters at the second line.

Cheticamp
  • 61,413
  • 10
  • 78
  • 131