从当前光标位置的EditText获取单词

时间:2013-08-14 07:58:01

标签: 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.setHeaderTitle(edittext.getText().toString().substring(edittext.getSelectionStart(), edittext.getSelectionEnd()));
    menu.add("Copy");
}

edittext有一些文字,例如“有些文字。还有一些文字”。用户单击“更多”,因此光标将位于单词“more”中的某些位置。我希望当用户长按这个词我可以得到“更多”这个词,以及光标下的其他词。

5 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:4)

有更好更简单的解决方案:在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
}

答案 2 :(得分:1)

请优化以下代码。如果您有更多规格,请告诉我。

//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();

答案 3 :(得分:1)

我相信BreakIterator是这里的优秀解决方案。它避免了必须遍历整个字符串并自己进行模式匹配。除了一个简单的空格字符(逗号,句号等)之外,它还可以找到单词边界。

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

如果您想长时间使用,请将其放在onLongPress的{​​{1}}方法中。

另见

答案 4 :(得分:0)

@Ali感谢您提供解决方案。

以下是优化变体,如果找到该单词,则中断

此解决方案不会创建Spannable ,因为找不到该单词不需要。

@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;
}

示例:获取当前光标位置

的单词
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+");

Java 正则表达式文档(正则表达式):https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html