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

时间:2015-06-24 07:55:38

标签: android android-edittext

我只需要当前光标位置的字符串而不是edittext中的所有字符串。例如,如果我正在打字" Hello world,你们好吗?"然后,如果我的光标在"是"那么我只需要字符串"是"。

3 个答案:

答案 0 :(得分:3)

试试这个

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?

答案 1 :(得分:2)

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

答案 2 :(得分:1)

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

相关问题