Android: Edittext- get current line

前端 未结 3 1960
说谎
说谎 2021-01-05 20:10

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 t

3条回答
  •  礼貌的吻别
    2021-01-05 20:34

    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!

提交回复
热议问题