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
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);
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 ortextview.post { /* get coordinates */ }
in Kotlin
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With