Better way to get all the text in an EditText from an InputConnection?
Asked Answered
R

2

14

I've written an IME (InputMethodService) and I need to get all the text from the EditText it is editing. I know one way:

InputConnection inputConnection = getCurrentInputConnection();
inputConnection.append(inputConnection.getTextBeforeCursor(9999, 0))
.append(inputConnection.getTextAfterCursor(9999, 0));

It works, but it seems pretty stupid and clunky. However there is no such method InputConnection.getText().

Is there a better way?

P.S. I cannot access the EditText from my IME because it belongs to the parent app so please don't tell me to use EditText.getText(), unless you know a way to get the EditText!

Ranna answered 16/9, 2011 at 4:43 Comment(1)
Also, just to note, getTextBeforeCursor and getTextAfterCursor do not include the selected text (if there is a selection).Conveyor
M
8

Here is also another way to do it:

inputConnection.performContextMenuAction(android.R.id.selectAll);
CharSequence sData =  inputConnection.getSelectedText(0);
Marking answered 16/9, 2011 at 5:13 Comment(2)
Unfortunately that method is not available in v2.1 (which I'm still using), but thank you anyway and I up-voted because it is still a correct answer.Ranna
Did someone try that in Marshmallow? Because it didn't work here. Thanks!Storax
Y
23

My solution is to use getExtractedText(). I am not sure if this has some limitations, but has worked for me so far.

CharSequence currentText = inputConnection.getExtractedText(new ExtractedTextRequest(), 0).text;
Year answered 27/6, 2012 at 11:54 Comment(7)
Seems this not working anymore in Marshmallow 6 and 6.0.1, I tested it many times and I got some users confirm that.Storax
It's not working properly in some application like I have faced an issue in Ms Word app. In Ms Word, I didn't get a whole text. Have you found any solution for that?Siloum
@MohammadAlBanna & Kinamand have u found any solution guy?Siloum
@PravinSuthar Have you found any solution ? If yes Can you please paste it here?. I need it.Klee
@ChiragPrajapati not yet bro.Siloum
@PravinSuthar Let me please know about how you have handled it in your app?Klee
@ChiragPrajapati I don't have any solution for this if you have plz share with me.Siloum
M
8

Here is also another way to do it:

inputConnection.performContextMenuAction(android.R.id.selectAll);
CharSequence sData =  inputConnection.getSelectedText(0);
Marking answered 16/9, 2011 at 5:13 Comment(2)
Unfortunately that method is not available in v2.1 (which I'm still using), but thank you anyway and I up-voted because it is still a correct answer.Ranna
Did someone try that in Marshmallow? Because it didn't work here. Thanks!Storax

© 2022 - 2024 — McMap. All rights reserved.