我是 android 编程的新手。我向 edittext 添加了一个上下文菜单。我希望在长按时得到光标下的单词。
我可以通过以下代码获取选定的文本。
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
EditText edittext = (EditText)findViewById(R.id.editText1);
menu.setHeaderTitle(edittext.getText().toString().substring(edittext.getSelectionStart(), edittext.getSelectionEnd()));
menu.add("Copy");
}
edittext 有一些文本,例如“一些文本。一些更多的文本”。当用户点击“more”时,光标会在“more”这个词的某个地方。当用户长按单词时我想得到光标下的单词“more”和其他单词。
最佳答案
有更好更简单的解决方案:在android中使用模式
public String getCurrentWord(EditText 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();
break;
}
}
return currentWord; // This is current word
}
关于android - 从当前光标位置的 EditText 中获取单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18226140/