Android TextView and getting line of text

前端 未结 2 1589
轻奢々
轻奢々 2020-12-15 09:41

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
相关标签:
2条回答
  • 2020-12-15 10:00

    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;
    }
    
    0 讨论(0)
  • 2020-12-15 10:22

    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

    0 讨论(0)
提交回复
热议问题