In an edittext is there a method for getting the current line of the cursor? If not I will write my own method, but just wanted to check. If I do write my own method would the best method be to go through every character in the edittext until selectionstart and count the number of \n's using a For loop, or is there a better way? Thanks!
3 Answers
Just to let people know:
There is a better way to do this then Doug Paul has suggested by using the getLineForOffset(selection)
:
public int getCurrentCursorLine(EditText editText)
{
int selectionStart = Selection.getSelectionStart(editText.getText());
Layout layout = editText.getLayout();
if (!(selectionStart == -1)) {
return layout.getLineForOffset(selectionStart);
}
return -1;
}

- 2,681
- 21
- 31

- 2,441
- 3
- 23
- 31
-
Nice, that is indeed better! I had pored over the API looking for a method to do this job but didn't find it at the time. That's apparently been in there since API level 1, though. – Doug Paul Aug 01 '12 at 17:44
I can't find a simple way to get this information either, so your approach seems about right. Don't forget to check for the case where getSelectionStart()
returns 0. You can make the code reusable by putting it in a static utility method, like this:
private int getCurrentCursorLine(Editable editable) {
int selectionStartPos = Selection.getSelectionStart(editable);
if (selectionStartPos < 0) {
// There is no selection, so return -1 like getSelectionStart() does when there is no seleciton.
return -1;
}
String preSelectionStartText = editable.toString().substring(0, selectionStartPos);
return countOccurrences(preSelectionStartText, '\n');
}
The countOccurrences()
method is from this question, but you should use one of the better answers to that question (e.g. StringUtils.countMatches()
from commons lang) if feasible.
I have a full working example that demonstrates this method, so let me know if you need more help.
Hope this helps!
find the last index of "\n"using method lastindex=String.lastindexof("\n") then get a substring using method String.substring(lstindex,string.length).and you will get the last line in two lines of code.

- 7,509
- 31
- 126
- 189
-
The question is about finding the current line that the cursor is on, but your answer doesn't seem to address the position of the cursor. – Doug Paul Oct 02 '11 at 17:55