Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 990
Para Style Avatar asked Oct 27 '22 18:10

Para Style


1 Answers

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

like image 130
Gibolt Avatar answered Nov 11 '22 10:11

Gibolt