简体   繁体   中英

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);

Thank you @mohammadReza Abiri. I found the solution for this.

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

        int selectionStart = extractedText.selectionStart;
        int selectionEnd = extractedText.selectionEnd;

        mLatinIme.getCurrentInputConnection().setSelection(selectionStart, selectionEnd + 1);

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);

            }
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM