views:

520

answers:

3

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?

+4  A: 

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.

mbaird
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
A: 

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
A: 

I have one doubt where to write this function. Say suppose i want to pass the selected text to Database as the string... Now where i have to write the Three lines ??

int startpoint = mBodyText.getSelectionStart();

int endpoint = mBodyText.getSelectionEnd();

selectedText = mBodyText.getText().toString().substring(startpoint,endpoint);

I have written them in one click function , but showing the error. And if i written them in the onCreate function then showing null string. I am changing the Notepad application little bit. Any help plz....:-(

Ashok