I need only string at current cursor position not all the string from edittext. For example, If I am typing "Hello world, how are you all?" then, if my cursor is at "are" then I need only string "are".
Asked
Active
Viewed 102 times
-2
-
if the cursor is in middle then i will manage I need only the currently typed text in edittext at cursor position – bimal thapa Jun 24 '15 at 08:00
-
I have tried using ontextchanged listener and using the charsequence and count. But I need shorter way to get the string at current cursor position. – bimal thapa Jun 24 '15 at 08:01
3 Answers
3
Try this
EditText et=(EditText)findViewById(R.id.edit);
int startSelection=et.getSelectionStart();
int endSelection=et.getSelectionEnd();
String selectedText = et.getText().toString().substring(startSelection, endSelection);
Take a look here How to get selected text from edittext in android?
2
Solution using pattern in Android.
EditText editText = (EditText)findViewById(R.id.edittext);
Spannable textSpan = editText.getText();
final int selection = editText.getSelectionStart();
final Pattern pattern = Pattern.compile("\\w+");
final Matcher matcher = pattern.matcher(textSpan);
int start = 0;
int end = 0;
String currentWord = "";
while (matcher.find()) {
start = matcher.start();
end = matcher.end();
if (start <= selection && selection <= end) {
currentWord = textSpan.subSequence(start, end).toString();
}
}
Log.d("value", currentWord);

capt.swag
- 10,335
- 2
- 41
- 41
-
If this answer solved your query, you should mark this as correct @OP – capt.swag Jun 24 '15 at 10:02
2
Try using EditText.getSelectionStart()
to get the current position of the cursor

kiran kumar
- 1,402
- 17
- 34