1

So, I have an EditText view and my idea is on a, lets say for now, touch event to select and copy the touched word into clipboard memory. So far I can set Selection through offset, but it is only "", because getSelectionStart() = getSelectionEnd() = offset. How can I extend it until the next encountered whitespace or end/start of text.

How could I extend one such selection in the above described manner?

Code so far:

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

Thanks.

Dimitar
  • 4,402
  • 4
  • 31
  • 47

1 Answers1

2

You should be able to calculate the index of the next space after your start selection index and use that (endIndex below in my example) instead of getSelectionEnd() when calling substring when you're setting your selectedText.

For example:

String substringFromStartSelection = getText().toString().substring (getSelectionStart());
int nextSpaceIndex = substringFromStartSelection.indexOf(" "); 
int selectionEnd = getSelectionStart() + nextSpaceIndex; 
Karen Forde
  • 1,117
  • 8
  • 20
  • 1
    Won't work if the word ends with a period, or space, or quote, or .... Another approach is to use `BreakIterator.getWordInstance()`. See https://stackoverflow.com/questions/42219292/how-does-breakiterator-work-in-android – Suragch Jun 17 '17 at 08:07