Par*_*yle 5 android character char textview coordinates
是否可以从 Android 中 TextView 中的字符获取 x 坐标?我不是在寻找 TextView 本身的坐标,我需要 TextView 中最后一个字符的坐标(多行)
提前致谢
以下是如何获取特定字符的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)
如果您希望多次使用它:
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)
注意:为了确保布局不为 null
textview.post(() -> { /* get coordinates */ }),您可以在 Java 或textview.post { /* get coordinates */ }Kotlin 中调用
使用:
layout.getPrimaryHorizontal(int offset)
Run Code Online (Sandbox Code Playgroud)
使用起来很简单。您只需使用布局所使用的文本长度来迭代布局即可。
它将返回Character的x。所以我仍然从layout.getLineTop(). 顺便说一句,如果您正在使用layout.getLineTop(),请注意有一些奇怪的行为,可能是一个错误。
| 归档时间: |
|
| 查看次数: |
1089 次 |
| 最近记录: |