Android - 如何在文本视图中获取字符的坐标

Par*_*yle 5 android character char textview coordinates

是否可以从 Android 中 TextView 中的字符获取 x 坐标?我不是在寻找 TextView 本身的坐标,我需要 TextView 中最后一个字符的坐标(多行)

提前致谢

Gib*_*olt 7

Java解决方案

以下是如何获取特定字符的x 和坐标。 是 textView 字符串中所需字符的索引。这些坐标是相对于父容器的yoffset

Layout layout = textView.getLayout();
if (layout == null) { // Layout may be null right after change to the text view
    // Do nothing
}

int lineOfText = layout.getLineForOffset(offset);
int xCoordinate = (int) layout.getPrimaryHorizontal(offset);
int yCoordinate = layout.getLineTop(lineOfText);
Run Code Online (Sandbox Code Playgroud)

Kotlin 扩展函数

如果您希望多次使用它:

fun TextView.charLocation(offset: Int): Point? {
    layout ?: return null // Layout may be null right after change to the text view

    val lineOfText = layout.getLineForOffset(offset)
    val xCoordinate = layout.getPrimaryHorizontal(offset).toInt()
    val yCoordinate = layout.getLineTop(lineOfText)
    return Point(xCoordinate, yCoordinate) 
}
Run Code Online (Sandbox Code Playgroud)

注意:为了确保布局不为 nulltextview.post(() -> { /* get coordinates */ }) ,您可以在 Java 或textview.post { /* get coordinates */ }Kotlin 中调用


Seb*_*xon 0

使用:

layout.getPrimaryHorizontal(int offset)
Run Code Online (Sandbox Code Playgroud)

使用起来很简单。您只需使用布局所使用的文本长度来迭代布局即可。

它将返回Character的x。所以我仍然从layout.getLineTop(). 顺便说一句,如果您正在使用layout.getLineTop(),请注意有一些奇怪的行为,可能是一个错误。