Android TextView 和获取文本行

发布于 2025-01-07 06:21:43 字数 111 浏览 3 评论 0原文

我有一个 TextView,其文本可以运行多行。创建并动态设置后,我想

  1. 获取给定行上的文本,并
  2. 了解该行的宽度和高度。

我该怎么做?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

趴在窗边数星星i 2025-01-14 06:21:43

如果我理解正确的话,问题 2 的答案是:

textView.getLineBounds (int line, Rect bounds)

以像素为单位的宽度应该是 abs(bounds.right -bounds.left);高度是 abs(bounds.bottom -bounds.top)

你的第一个问题有点棘手,但这样的事情应该可以实现所需的魔力:

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

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;
}
近箐 2025-01-14 06:21:43

对于第一个问题:

之前选择的答案没有适合我,因为我的文本视图有自动换行。
使用以下行从给定行号“i”获取文本

Kotlin:

var textofline:String = textview.text.subSequence(textview.layout.getLineStart(i), textview.layout.getLineEnd(i)).toString()

如果缺少解释,请告诉我。

PS:我不是安卓高手。只是分享我的知识以防有人觉得有用

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文