Java 解决方案
这是有关如何获取特定字符的x
和坐标的完整代码。是's 文本中所需字符的索引。这些坐标是相对于父容器的y
offset
textView
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);
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)
}
注意:为确保布局不为空,您可以textview.post(() -> { /* get coordinates */ })
在 Java 或textview.post { /* get coordinates */ }
Kotlin中调用