Android 从当前光标位置的编辑文本中获取单词

Android 从当前光标位置的编辑文本中获取单词,android,text,cursor,android-edittext,Android,Text,Cursor,Android Edittext,我是android编程新手。我在edittext中添加了上下文菜单。我希望我能在长按时把字放在光标下。请帮忙。我可以通过以下代码获得所选文本 @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { EditText edittext = (EditText)findViewById(R.id.editText1); menu.setHeaderT

我是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");
}

编辑文本有一些文本,例如“一些文本。更多文本”。用户单击“更多”,因此光标将位于单词“更多”中的某个位置。我希望当用户长按单词时,我可以在光标下找到单词“more”等其他单词。

请尝试以下代码,因为它已优化。如果您有更多的规格,请告诉我

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

int startSelection = et.getSelectionStart();

String selectedWord = "";
int length = 0;

for(String currentWord : et.getText().toString().split(" ")) {
    System.out.println(currentWord);
    length = length + currentWord.length() + 1;
    if(length > startSelection) {
        selectedWord = currentWord;
        break;
    }
}

System.out.println("Selected word is: " + selectedWord);
//String str = editTextView.getText().toString(); //suppose edittext has "Hello World!" 
int selectionStart = editTextView.getSelectionStart(); // Suppose cursor is at 2 position
int lastSpaceIndex = str.lastIndexOf(" ", selectionStart - 1);
int indexOf = str.indexOf(" ", lastSpaceIndex + 1);
String searchToken = str.substring(lastSpaceIndex + 1, indexOf == -1 ? str.length() : indexOf);

Toast.makeText(this, "Current word is :" + searchToken, Toast.LENGTH_SHORT).show();

有更好更简单的解决方案:在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
}
公共字符串getCurrentWord(编辑文本){ Spannable textSpan=editText.getText(); final int selection=editText.getSelectionStart(); 最终模式=模式。编译(\\w+); 最终匹配器匹配器=pattern.Matcher(textSpan); int start=0; int end=0; 字符串currentWord=“”; while(matcher.find()){ start=matcher.start(); end=matcher.end();
如果(开始@Ali),感谢您提供您的解决方案

这里有一个优化的变体,如果找到单词,它会中断

此解决方案不创建Spanable,因为不需要它来查找单词

@NonNull
public static String getWordAtIndex(@NonNull String text, @IntRange(from = 0) int index) {
    String wordAtIndex = "";

    // w = word character: [a-zA-Z_0-9]
    final Pattern pattern = Pattern.compile("\\w+");
    final Matcher matcher = pattern.matcher(text);

    int startIndex;
    int endIndex;

    while (matcher.find()) {
        startIndex = matcher.start();
        endIndex = matcher.end();

        if ((startIndex <= index) && (index <= endIndex)) {
            wordAtIndex = text.subSequence(startIndex, endIndex).toString();
            break;
        }
    }
    return wordAtIndex;
}
如果要查找所有连接的字符(包括标点符号),请使用此选项:


Javaregex文档(正则表达式):

我认为
BreakIterator
是这里最好的解决方案。它避免了在整个字符串上循环并自己进行模式匹配。它还可以找到单词边界,而不仅仅是一个简单的空格字符(逗号、句点等)

如果你想长时间按下它,只需将其放入
手势检测器的
onLongPress
方法中即可

另请参见


需要初始化currentWord。
currentWord=“”;
。除此之外,这是一个很好的解决方案。这是最灵活的解决方案。但我使用“\w+(\-\w+)”作为正则表达式,因为有包含连字符的单词。例如,按视图付费。这不会选择除空格以外的其他单词。另一种方法:使用
BreakIterator.getWordInstance()
。请只看一个简单的注释,对于任何想处理这种情况的人来说,这里可能不够清楚:如果光标位置在第一个单词-->中,则表示lastSpaceIndex将为-1,这一点不必在意,因为当我们对字符串进行子串时,我们将+1添加到lastSpaceIndex-->中,表示它将变为0,并且它是字符串的第一个索引.
String text = editText.getText().toString();
int cursorPosition = editText.getSelectionStart();

String wordAtCursorPosition = getWordAtIndex(text, cursorPosition);
// S = non-whitespace character: [^\s]
final Pattern pattern = Pattern.compile("\\S+");
// assuming that only the cursor is showing, no selected range
int cursorPosition = editText.getSelectionStart();

// initialize the BreakIterator
BreakIterator iterator = BreakIterator.getWordInstance();
iterator.setText(editText.getText().toString());

// find the word boundaries before and after the cursor position
int wordStart;
if (iterator.isBoundary(cursorPosition)) {
    wordStart = cursorPosition;
} else {
    wordStart = iterator.preceding(cursorPosition);
}
int wordEnd = iterator.following(cursorPosition);

// get the word
CharSequence word = editText.getText().subSequence(wordStart, wordEnd);