Para Style
Para Style

Reputation: 81

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

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

Upvotes: 8

Views: 2750

Answers (3)

Gibolt
Gibolt

Reputation: 47069

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

Upvotes: 8

MatthewLC
MatthewLC

Reputation: 311

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()?

Upvotes: 0

Sebastian Dixon
Sebastian Dixon

Reputation: 75

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.

Upvotes: 0

Related Questions