Android - 如何获取 TextView 中字符的坐标

标签 android char textview character coordinates

是否可以从 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 or textview.post { /* get coordinates */ } in Kotlin

关于Android - 如何获取 TextView 中字符的坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54946269/

相关文章:

android - 更改 WiFi-Direct IP 范围?在 Android WiFi-Direct 中强制使用 IPv6?

android - 如何在android中使微调器背景透明?

c++ - 在 std::set 容器中使用常量字符指针:内存消耗

android - 如何在 TextView 字段中设置永久文本?

Android TextView 字体大小更改后未调整大小

Android 删除换行符

android - 如何处理Fragment类ListView的按钮事件?

android - 如何在 android 的自定义 TextView 控件中更改字母的颜色?

SQL 2008 压缩

c++ - C++中字符数组的意外输出