如何在 TextView 中的特定行获取文本 [英] How do I get the text at a specific line in a TextView
问题描述
我有一个 X 行长的 TextView
.如何获取第 3 行的文本?
I have a TextView
that is X lines long. How do I get the text that is at, say, line 3?
示例:我有这个 TextView
这是第 1 行
这是第 2 行
这是第 3 行
我希望能够自己在这些行中的任何一行获取 String
,例如在第 3 行获取 String
将返回这是行3".搜索换行符不是我需要的解决方案,因为它没有考虑文本换行.
I want to be able to get the String
at any one of these lines by itself, such as getting the String
at line 3 would return "And this is line 3". Searching for line breaks is not the solution I need, as it doesn't take into account text wrapping.
推荐答案
您可以使用 textView.getLayout().getLineStart(int line)
和 getLineEnd
找到文本中的字符偏移量.
You can use textView.getLayout().getLineStart(int line)
and getLineEnd
to find the character offsets in the text.
然后你可以只使用 textView.getText().substring(start, end)
-- 如果你使用 Spannables 进行格式化/等,则可以使用 subsequence.
Then you can just use textView.getText().substring(start, end)
-- or subsequence if you are using Spannables for formatting/etc.
这篇关于如何在 TextView 中的特定行获取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!