如何从 edittext 中获取单个字符串?

How to get single string from edittext?

我只需要当前光标位置的字符串,而不是 edittext 中的所有字符串。例如,如果我输入 "Hello world, how are you all?",那么如果我的光标位于 "are",那么我只需要字符串 "are".

试试这个

EditText et=(EditText)findViewById(R.id.edit);

int startSelection=et.getSelectionStart();
int endSelection=et.getSelectionEnd();

String selectedText = et.getText().toString().substring(startSelection, endSelection);

看这里How to get selected text from edittext in android?

解决方案使用 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);

尝试使用EditText.getSelectionStart()获取光标的当前位置