How do I get the cursor position x,y in an EditText
in Android? (where x is the line# and y is the column#)
Asked
Active
Viewed 1.0k times
18
-
1What do you mean by (x,y) in reference to a cursor? (Line#,Column#)? – devunwired Feb 18 '11 at 17:28
-
Yes!I want get cursor (Line#,Column#).You can help me? – hieubk Feb 19 '11 at 01:57
2 Answers
47
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.

Randy Sugianto 'Yuku'
- 71,383
- 57
- 178
- 228
-
This was a huge help as I am working on this question: http://stackoverflow.com/questions/25036816/custom-rotated-edittext-view-with-working-selection-cursor-location-etc – Suragch Nov 21 '14 at 15:39
4
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);

Henry Thompson
- 2,441
- 3
- 23
- 31