Android-如何在textview中获取字符的坐标
在Android中,是否可以从TextView中的角色获取x坐标? 我不是在寻找文本视图本身的坐标,我需要文本视图中最后一个字符的坐标(多行) 提前感谢使用:Android-如何在textview中获取字符的坐标,android,char,textview,character,coordinates,Android,Char,Textview,Character,Coordinates,在Android中,是否可以从TextView中的角色获取x坐标? 我不是在寻找文本视图本身的坐标,我需要文本视图中最后一个字符的坐标(多行) 提前感谢使用: layout.getPrimaryHorizontal(int offset) 它使用起来很简单。您只需使用布局使用的文本长度来迭代布局 它将返回字符的x。所以我仍然从layout.getLineTop()中获取行。顺便说一句,如果您使用的是layout.getLineTop(),请注意有一些奇怪的行为,可能是一个bug。Java解决方
layout.getPrimaryHorizontal(int offset)
它使用起来很简单。您只需使用布局使用的文本长度来迭代布局
它将返回字符的x。所以我仍然从layout.getLineTop()
中获取行。顺便说一句,如果您使用的是layout.getLineTop()
,请注意有一些奇怪的行为,可能是一个bug。Java解决方案
下面是如何获取特定字符的x
和y
坐标<代码>偏移量是文本视图字符串中所需字符的索引。这些坐标是相对于父容器的
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)
}
注意:为了确保布局不为空,您可以在Java中调用textview.post(()->{/*get coordinates*/})
,或者在Kotlin中调用textview.post{/*get coordinates*/}
给定一个跨度有一个或多个段落,尝试获取整个跨度的最后一个字符不起作用。是否有其他方法可以获得getPrimaryHorizontal()的相同结果?的可能重复项