18

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

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
hieubk
  • 201
  • 1
  • 2
  • 6

2 Answers2

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