javaandroidandroid-softkeyboardrichtexteditinginputconnection

How to find the position of Cursor to select text from that position in Edit text?


I am working on Keyboard for android devices where i am Text editing options like Google Keyboard like (Text selection, copy paste etc). for example i typed a text ABSCEONDER and now i want to selection some portion of text. like i want text selection from position E. What i did is i drooped cursor at position E manually. now how do i find the position of Cursor to select text from that position? can any one help?

 ExtractedText extractedText = mLatinIme.getCurrentInputConnection().getExtractedText(new ExtractedTextRequest(), 0);
                if (extractedText == null || extractedText.text == null) return;
                int index = extractedText.text.length();
                mLatinIme.getCurrentInputConnection().setSelection(0, index);

Solution

  • you can get the cursor position from your EditText like this :

    editText.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    
                }
    
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
    
                }
    
                @Override
                public void afterTextChanged(Editable s) {
    
                  int pos = editText.getSelectionStart();
                  Layout layout = editText.getLayout();
                  float x = layout.getPrimaryHorizontal(pos);
    
                }
            });