是否可以从 Android 中的 TextView 中的字符获取 x 坐标? 我不是在寻找 TextView 本身的坐标,我需要 TextView 中最后一个字符的坐标(多行)
提前致谢
最佳答案
Java 解决方案
下面是如何获取特定字符的 x
和 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)
}
NOTE: To ensure layout is not null, you can call
textview.post(() -> { /* get coordinates */ })
in Java ortextview.post { /* get coordinates */ }
in Kotlin
关于Android - 如何获取 TextView 中字符的坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54946269/