Android - How to get the coordinates of a character in a textview
Asked Answered
P

3

8

Is it possible to get the x coordinate from a character in a TextView in Android? I'm not looking for the coordinate of the TextView itself, I need the coordinate of the last character in the TextView (multi line)

Thanks in advance

Parboil answered 1/3, 2019 at 14:4 Comment(1)
Possible duplicate of Find exact coordinates of a single Character inside a TextViewMorganmorgana
M
8

Java Solution

Here is how to get the x and y coordinates of a specific character. offset is the index of the desired character in the textView's String. These coordinates are relative to the parent container

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 Extension Function

If you expect to use this more than once:

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

Morten answered 24/6, 2019 at 16:4 Comment(0)
M
0

Use:

layout.getPrimaryHorizontal(int offset)

It is simple to use. You just iterate through the layout using the length of the text it uses.

It will return the x of the Character . So lines I'm still getting from the layout.getLineTop() . By the way, if you are using the layout.getLineTop() , note that there is some strange behaviour, possibly a bug.

Morganmorgana answered 1/3, 2019 at 14:12 Comment(0)
I
0

Given a span that has one or more paragraphs, try to get the last character of the entire span dosen't work. Is there another way to get the same result of getPrimaryHorizontal()?

Indubitable answered 24/9, 2019 at 17:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.