如何在 EditText 中将 Selection 扩展到整个单词?

How to extend Selection to a whole word in EditText?

所以,我有一个 EditText 视图,我的想法是,让我们说现在,触摸事件 select 并将触摸的单词复制到剪贴板内存中。到目前为止,我可以通过偏移设置选择,但它只是"",因为getSelectionStart() = getSelectionEnd() = offset。我怎样才能将它扩展到下一个遇到空格或 end/start 文本。

如何以上述方式扩展这样的 selection?

到目前为止的代码:

@Override
public boolean onTouch(View v, MotionEvent event)
{
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        float x = event.getX() + getScrollX();
        int offset = getOffset(event);
        if(offset != Integer.MIN_VALUE){
                setSelection(offset);
                String selectedText = getText().toString()
                            .substring(getSelectionStart(), getSelectionEnd());

                   //TODO: extend selection otherwise copies ""

                putInClipMemory(selectedText);
        }
    return true;
} 

谢谢。

您应该能够在开始选择索引之后计算下一个 space 的索引,并在调用 substring 当你设置你的 selectedText.

例如:

String substringFromStartSelection = getText().toString().substring (getSelectionStart());
int nextSpaceIndex = substringFromStartSelection.indexOf(" "); 
int selectionEnd = getSelectionStart() + nextSpaceIndex;