10

I'm trying to implement a copy/paste function. How can I get a selection of text from an EditText?

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

blabla onclicklistener on a button:

int startSelection=et.getSelectionStart();
int endSelection=et.getSelectionEnd();

Then I'm stuck. Any ideas?

thkala
  • 84,049
  • 23
  • 157
  • 201
Laise
  • 101
  • 1
  • 1
  • 3

5 Answers5

16

Seems like you've already done the hard part by finding what the selected area is. Now you just need to pull that substring out of the full text.

Try this:

String selectedText = et.getText().substring(startSelection, endSelection);

It's just a basic Java String operation.

Mark B
  • 183,023
  • 24
  • 297
  • 295
  • 7
    A minor gripe with android is that getSelectionStart() and getSelectionEnd() refers to the order in which stuff was selected, which doesn't necessarily lead to Start < End... (not a big deal here, but nice to remember, saves a few OutOfBounds') – andy Feb 01 '10 at 18:29
  • Guys, i'm doing like your answer, but my getselectionStart() and getSelectionEnd() method are with problems. Both are returning the same value. – FpontoDesenv Oct 25 '13 at 23:28
  • et.getText() returns an editable. substring() nees a String. You need to add toString(). That is - et.getText().toString().substring(start, end) – earlcasper Jan 29 '15 at 05:37
0

you don't need to do all this, just long press on edit text it will show you all relevant options to Copy/Paste/Select etc. If you want to save the text use the method shown by mbaird

Rs9766
  • 173
  • 2
  • 11
0

String selectedText = et.getText().toString().substring(startSelection, endSelection);
getText() returns an editable. substring needs a String. toString() connects them properly.

earlcasper
  • 915
  • 10
  • 8
0

You can do it this way to get the selected text from EditText:

EditText editText = (EditText) findViewById(R.id.editText3);
int min = 0;
int max = editText.getText().length();
if (editText.isFocused()) {
    final int selStart = editText.getSelectionStart();
    final int selEnd = editText.getSelectionEnd();
    min = Math.max(0, Math.min(selStart, selEnd));
    max = Math.max(0, Math.max(selStart, selEnd));
}
// here is your selected text
final CharSequence selectedText = editText.getText().subSequence(min, max);
String text = selectedText.toString();
Schemetrical
  • 5,506
  • 2
  • 26
  • 43
SKG
  • 346
  • 4
  • 11
0

You should use a special function from the Editable object:

Editable txt = et.getText();
txt.replace(int st, int en, CharSequence source)

This command replaces the part specified with (st..en) with the String (CharSequence).

Harald Schilly
  • 1,098
  • 1
  • 14
  • 15