Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get cursor position (x,y) in EditText android

Tags:

android

How do I get the cursor position x,y in an EditText in Android? (where x is the line# and y is the column#)

like image 209
hieubk Avatar asked Feb 18 '11 17:02

hieubk


2 Answers

int pos = editText.getSelectionStart();
Layout layout = editText.getLayout();
int line = layout.getLineForOffset(pos);
int baseline = layout.getLineBaseline(line);
int ascent = layout.getLineAscent(line);
float x = layout.getPrimaryHorizontal(pos);
float y = baseline + ascent;

and there you get the x, y positions in pixels of the cursor.

like image 136
Randy Sugianto 'Yuku' Avatar answered Sep 28 '22 18:09

Randy Sugianto 'Yuku'


You can find the current selection's Line Number and Column like this:

// Get the current selection's line number
int line = edittext.getLayout().getLineForOffset(edittext.getSelectionStart());

// Find the index for the start of the selected line. Subtract that from the current selection's index
int column = edittext.getSelectionStart() - edittext.getLayout().getLineStart(line);
like image 22
Henry Thompson Avatar answered Sep 28 '22 17:09

Henry Thompson