12

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?

Ken
  • 30,811
  • 34
  • 116
  • 155

2 Answers2

27

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;
}
Ranjithkumar
  • 16,071
  • 12
  • 120
  • 159
CjS
  • 2,037
  • 2
  • 21
  • 29
  • 1
    You'll need to perform a `toString()` on it. I would also do a check to make sure `textView.getText != null` to avoid compiler warnings. – LukeWaggoner May 14 '14 at 19:26
  • Great hint about getting the TextView layout and querying it for the line size! exactly what I was looking for – Noa Drach Feb 15 '16 at 12:32
0

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

Santhosh
  • 81
  • 2
  • 11