问题描述
我复制了另一个网站的链接,并希望通过Android中的按钮将复制的文本传递到EditText字段中。
解决方法
要从剪贴板中获取数据并将其粘贴到您的EditText中,请执行以下操作:
// get a reference to the ClipboardManager
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
// you will save the text in here later
String pasteData = "";
// Examines the item on the clipboard. If getText() does not return null,the clip item contains the
// text. Assumes that this application can only handle one item at a time.
ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0);
// Gets the clipboard as text.
pasteData = item.getText();
// If the string contains data,then the paste operation is done
if (pasteData != null) {
return true;
// The clipboard does not contain text. If it contains a URI,attempts to get data from it
} else {
Uri pasteUri = item.getUri();
// If the URI contains something,try to get text from it
if (pasteUri != null) {
// calls a routine to resolve the URI and get data from it. This routine is not
// presented here.
pasteData = resolveUri(Uri);
return true;
} else {
// Something is wrong. The MIME type was plain text,but the clipboard does not contain either
// text or a Uri. Report an error.
Log.e(TAG,"Clipboard contains an invalid data type");
return false;
}
}
// make sure you have gotten any text and then set in your edittext
if (pasteData != null && !pasteData.isEmpty()) {
editText.setText(pasteData)
}
编辑:
来源:https://developer.android.com/guide/topics/text/copy-paste#java