【问题标题】:How do I get the text at a specific line in a TextView如何在 TextView 中的特定行获取文本
【发布时间】:2011-06-07 23:07:08
【问题描述】:

我有一个 X 行长的TextView。如何获取第 3 行的文本?

例子:我有这个TextView

这是第 1 行

这是第 2 行

这是第 3 行

我希望能够单独在这些行中的任何一行获取String,例如在第 3 行获取String 将返回“这是第 3 行”。搜索换行符不是我需要的解决方案,因为它没有考虑文本换行。

【问题讨论】:

    标签: android textview


    【解决方案1】:

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

    然后你可以只使用textView.getText().substring(start, end) -- 如果你使用 Spannables 来格式化/等,则可以使用 subsequence。

    【讨论】:

    • 谢谢!我不知道TextView 有它自己的特殊布局,尽管它是有道理的。这正是我所需要的。
    【解决方案2】:

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

    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);
    }
    

    【讨论】:

      猜你喜欢
      • 2016-06-26
      • 1970-01-01
      • 1970-01-01
      • 2015-03-13
      • 2021-06-30
      • 1970-01-01
      • 2014-05-14
      • 2015-03-07
      • 1970-01-01
      相关资源
      最近更新 更多