如何在编辑文本中将选择扩展到整个单词?



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

我如何以上述方式扩展一个这样的选择?

到目前为止的代码:

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

谢谢。

您应该能够在开始选择索引之后计算下一个空间的索引,并使用它(在我的示例中endIndex下面),而不是在设置selectedText时调用substringgetSelectionEnd()

例如

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

最新更新