1

I have an EditText, and I want to display cursor info for user. But I can't get cursor position at the line which user is editing. For ex.

`The quick b|rown fox...` - Cursor @ line 0, symbol 13
`StackOverflow rule|s!` - Cursor @ line 1, symbol 20

How I can do that?

Excuse for my English, please.

Helisia
  • 568
  • 2
  • 7
  • 23

2 Answers2

0

You can get the Cursor position using the getSelectionStart() and getSelectionEnd() methods. If no text is highlighted, both getSelectionStart() and getSelectionEnd() return the position of the cursor. Eg:

myEditText.getSelectionStart();

or

myEditText.getSelectionEnd();

For getting line number

Use:

public int getCurrentCursorLine(EditText editText)
{    
int selectionStart = Selection.getSelectionStart(editText.getText());
Layout layout = editText.getLayout();

if (!(selectionStart == -1)) {
    return layout.getLineForOffset(selectionStart);
}

return -1;
}

source

Community
  • 1
  • 1
Viswanath Lekshmanan
  • 9,945
  • 1
  • 40
  • 64
  • Your code doesn't works properly. It returns ALL symbols count and ALL lines count, but I need to get cursor position at one line, not on all lines. – Helisia Dec 30 '13 at 14:19
0

The question is long ago. But I want to help people who arrive here. Here is what I got after researching java.util.regex.Matcher API. Good luck.

Below method converts charater index in ALL lines into that in SINGLE line. So you can use it in android programming like, getInLineOffsetFromStringOffset(editText.getText(),editText.getSelectionStart)

I have tested in all conditions like, single line or multiple line (some part of the code seems nesty due to controlling such behaviour), so you just copy and paste if you don't have time to investigate what these mean.

Note: To get your desired result as the question described, you just need to plus one the result.

public static int getInLineOffsetFromStringOffset(CharSequence src,int offset){
    Pattern p=Pattern.compile("(\r)|(\n)|(\n\r)");
    Matcher m=p.matcher(src);
    int x=offset;
    int start=0,end=0,lastEnd=0;
    if(m.find()){
        end=m.end();
        start=m.start();
        if(!(end>x))

            while(m.find()){
                lastEnd=end;
                end=m.end();
                start=m.start();
                if(end>x)
                    break;
            }
    }
    if(!(end>x)){
        lastEnd=end;
        start=src.length();
        end=src.length();
    }
    return (start<x)?-1:(x-(lastEnd));
}
johnkarka
  • 365
  • 2
  • 14