Ken
Ken

Reputation: 31161

Android TextView and getting line of text

I have a TextView whose text can run to many lines. Once it has been created and set dynamically, I'd like to

  1. Get the text on a given line, and
  2. Know the width and height of this line.

How do I do this?

Upvotes: 12

Views: 11427

Answers (2)

Santhosh
Santhosh

Reputation: 91

For the First question:

The previous selected answer didn't make the cut for me as my textview had word wrap. Use the following line to get the text from the given line number 'i'

Kotlin:

var textofline:String = textview.text.subSequence(textview.layout.getLineStart(i), textview.layout.getLineEnd(i)).toString()

Let me know if it is lacking explanation.

PS: I'm no master in android. Just sharing my knowledge in case someone finds it useful

Upvotes: 0

CjS
CjS

Reputation: 2047

If I understand correctly the answer to question 2 is:

textView.getLineBounds (int line, Rect bounds)

The width in pixels should be abs(bounds.right - bounds.left); and the height is abs(bounds.bottom - bounds.top)

Your first question is a bit more tricky, but something like this should do the required magic:

Layout layout = textView.getLayout();
String text = textView.getText().toString();
int start=0;
int end;
for (int i=0; i<textView.getLineCount(); i++) {
    end = layout.getLineEnd(i);
    line[i] = text.substring(start,end);
    start = end;
}

Upvotes: 27

Related Questions