如何在TextView中的特定行获取文本

Jas*_*son 32 android textview

我有一个TextViewX线长.如何获取第3行的文本?

示例:我有这个 TextView

这是第1行

这是第2行

这是第3行

我希望能够自己获得String这些行中的任何一行,例如让第String3行返回"这就是第3行".搜索换行符不是我需要的解决方案,因为它没有考虑文本换行.

Chr*_*vey 44

您可以使用textView.getLayout().getLineStart(int line)和getLineEnd来查找文本中的字符偏移量.

然后你可以使用textView.getText().substring(start,end) - 或者如果你使用Spannables进行格式化等的子序列.


Sur*_*gch 9

这是一些代码来补充接受的答案:

List<CharSequence> lines = new ArrayList<>();
int count = textView.getLineCount();
for (int line = 0; line < count; line++) {
    int start = textView.getLayout().getLineStart(line);
    int end = textView.getLayout().getLineEnd(line);
    CharSequence substring = textView.getText().subSequence(start, end);
    lines.add(substring);
}
Run Code Online (Sandbox Code Playgroud)