Search code examples
androidandroid-edittexttext-cursor

Get word from EditText on current cursor position


I am new to android programing. I added a context menu to edittext. I wish to get the word under the cursor on long press.

I can get selected text by following code.

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    EditText edittext = (EditText)findViewById(R.id.editText1);
    menu.setHeaderTitle(edittext.getText().toString().substring(edittext.getSelectionStart(), edittext.getSelectionEnd()));
    menu.add("Copy");
}

edittext has some text e.g "Some text. Some more text". When the user clicks on "more", the cursor will be in some where in the word "more". When the user long presses the word I want to get the word "more" and other words under the cursor.


Solution

  • EditText et = (EditText) findViewById(R.id.xx);
    
    int startSelection = et.getSelectionStart();
    
    String selectedWord = "";
    int length = 0;
    
    for(String currentWord : et.getText().toString().split(" ")) {
        System.out.println(currentWord);
        length = length + currentWord.length() + 1;
        if(length > startSelection) {
            selectedWord = currentWord;
            break;
        }
    }
    
    System.out.println("Selected word is: " + selectedWord);