Android - get selection of text from EditText

2019-01-18 14:20发布

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?

5条回答
相关推荐>>
2楼-- · 2019-01-18 14:35

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).

查看更多
Luminary・发光体
3楼-- · 2019-01-18 14:36

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();
查看更多
4楼-- · 2019-01-18 14:42

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.

查看更多
5楼-- · 2019-01-18 14:47

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

查看更多
▲ chillily
6楼-- · 2019-01-18 14:51

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

查看更多
登录 后发表回答