下面列出了怎么用android.text.ClipboardManager的API类实例代码及写法,或者点击链接到github查看源代码。
@SuppressLint("NewApi")
@Override
public boolean onTextContextMenuItem(int id) {
if(id == android.R.id.paste){
@SuppressWarnings("deprecation")
ClipboardManager clip = (ClipboardManager)getContext().getSystemService(Context.CLIPBOARD_SERVICE);
String text = clip.getText().toString();
if(text.startsWith(ChatActivity.COPY_IMAGE)){
// intent.setDataAndType(Uri.fromFile(new File("/sdcard/mn1.jpg")), "image/*");
text = text.replace(ChatActivity.COPY_IMAGE, "");
Intent intent = new Intent(context,FXAlertDialog.class);
intent.putExtra("title", "发送以下图片?");
intent.putExtra("forwardImage", text);
intent.putExtra("cancel", true);
((Activity)context).startActivityForResult(intent,ChatActivity.REQUEST_CODE_COPY_AND_PASTE);
// clip.setText("");
}
}
return super.onTextContextMenuItem(id);
}
@SuppressLint("NewApi")
@Override
public boolean onTextContextMenuItem(int id) {
if(id == android.R.id.paste){
ClipboardManager clip = (ClipboardManager)getContext().getSystemService(Context.CLIPBOARD_SERVICE);
if (clip == null || clip.getText() == null) {
return false;
}
String text = clip.getText().toString();
if(text.startsWith(ChatActivity.COPY_IMAGE)){
// intent.setDataAndType(Uri.fromFile(new File("/sdcard/mn1.jpg")), "image/*");
text = text.replace(ChatActivity.COPY_IMAGE, "");
Intent intent = new Intent(context,AlertDialog.class);
String str = context.getResources().getString(R.string.Send_the_following_pictures);
intent.putExtra("title", str);
intent.putExtra("forwardImage", text);
intent.putExtra("cancel", true);
((Activity)context).startActivityForResult(intent,ChatActivity.REQUEST_CODE_COPY_AND_PASTE);
// clip.setText("");
}
}
return super.onTextContextMenuItem(id);
}
private void setup(final String intentkey, final int layoutid, boolean autoHide) {
String content = getIntent().getStringExtra(intentkey);
final View layout = findViewById(layoutid);
if (MiscUtils.isBlank(content) && autoHide) {
layout.setVisibility(View.GONE);
} else {
content = content == null ? "" : content;
((TextView) layout.findViewById(R.id.edit)).setText(content.trim());
layout.findViewById(R.id.copy).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final String text = getSelection((TextView) layout.findViewById(R.id.edit));
final ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
cm.setText(text);
final Toast toast = Toast.makeText(CopyActivity.this, AedictApp.format(R.string.copied, text), Toast.LENGTH_SHORT);
toast.show();
MainActivity.launch(CopyActivity.this, text);
}
});
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
if (selectedFragment != this) return false;
if (COPY_MENU_ITEM_TO_MASK.containsKey(item.getItemId())) {
// Generate the text to copy to the clipboard
String text = getCopyText(selectedEntry, COPY_MENU_ITEM_TO_MASK.get(item.getItemId()));
ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setText(text);
String label = item.getTitle().toString().substring(2); // this is ugly
String message = String.format(getString(R.string.copy_done), label);
Boast.showText(getActivity(), message, Toast.LENGTH_SHORT);
return true;
}
else if (item.getItemId() == R.id.menu_item_favorite) {
selectedEntry.findViewById(R.id.button_favorite).performClick();
return true;
}
else {
// Fall back to default behavior
return false;
}
}
private void reportError(final Throwable t) {
this.runOnUiThread(new Runnable() {
public void run() {
final StringWriter strWriter = new StringWriter();
PrintWriter pWriter = new PrintWriter(strWriter);
if (t instanceof RhinoException) {
String lineSource = ((RhinoException) t).lineSource();
if (lineSource != null) pWriter.println(lineSource);
}
t.printStackTrace(pWriter);
new AlertDialog.Builder(ManageScriptsActivity.this).setTitle(R.string.manage_patches_import_error).setMessage(strWriter.toString()).
setPositiveButton(android.R.string.ok, null).
setNeutralButton(android.R.string.copy, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface aDialog, int button) {
ClipboardManager mgr = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
mgr.setText(strWriter.toString());
}
}).
show();
}
});
}
private TextView handleBuildSuccessTextView(final String logUrl) {
TextView showText = new TextView(getActivity());
showText.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
showText.setPadding(15, 30, 15, 30);
showText.setText(getString(R.string.log_submit_activity__copy_this_url_and_add_it_to_your_issue, logUrl));
showText.setAutoLinkMask(Activity.RESULT_OK);
showText.setMovementMethod(LinkMovementMethod.getInstance());
showText.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
@SuppressWarnings("deprecation")
ClipboardManager manager =
(ClipboardManager) getActivity().getSystemService(Activity.CLIPBOARD_SERVICE);
manager.setText(logUrl);
Toast.makeText(getActivity(),
R.string.log_submit_activity__copied_to_clipboard,
Toast.LENGTH_SHORT).show();
return true;
}
});
Linkify.addLinks(showText, Linkify.WEB_URLS);
return showText;
}
/**
* {@inheritDoc}
*/
@SuppressWarnings("deprecation")
@Override
public boolean onContextItemSelected(MenuItem item)
{
if(item.getItemId() == R.id.copy_to_clipboard)
{
AdapterView.AdapterContextMenuInfo info
= (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
// Clicked position must be aligned to list headers count
int position = info.position - chatListView.getHeaderViewsCount();
// Gets clicked message
ChatMessage clickedMsg = chatListAdapter.getMessage(position);
// Copy message content to clipboard
ClipboardManager clipboardManager
= (ClipboardManager) getActivity()
.getSystemService(Context.CLIPBOARD_SERVICE);
clipboardManager.setText(clickedMsg.getContentForClipboard());
return true;
}
return super.onContextItemSelected(item);
}
private void handleCopyMessage(final Set<MessageRecord> messageRecords) {
List<MessageRecord> messageList = new LinkedList<>(messageRecords);
Collections.sort(messageList, new Comparator<MessageRecord>() {
@Override
public int compare(MessageRecord lhs, MessageRecord rhs) {
if (lhs.getDateReceived() < rhs.getDateReceived()) return -1;
else if (lhs.getDateReceived() == rhs.getDateReceived()) return 0;
else return 1;
}
});
StringBuilder bodyBuilder = new StringBuilder();
ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
for (MessageRecord messageRecord : messageList) {
String body = messageRecord.getDisplayBody(requireContext()).toString();
if (!TextUtils.isEmpty(body)) {
bodyBuilder.append(body).append('\n');
}
}
if (bodyBuilder.length() > 0 && bodyBuilder.charAt(bodyBuilder.length() - 1) == '\n') {
bodyBuilder.deleteCharAt(bodyBuilder.length() - 1);
}
String result = bodyBuilder.toString();
if (!TextUtils.isEmpty(result))
clipboard.setText(result);
}
private void initView() {
_fieldController = this.new TextFieldController();
_clipboardManager = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
_brush = new Paint();
_brush.setAntiAlias(true);
_brush.setTextSize(BASE_TEXT_SIZE_PIXELS);
_brushLine = new Paint();
_brushLine.setAntiAlias(true);
_brushLine.setTextSize(BASE_TEXT_SIZE_PIXELS);
//setBackgroundColor(_colorScheme.getColor(Colorable.BACKGROUND));
setLongClickable(true);
setFocusableInTouchMode(true);
setHapticFeedbackEnabled(true);
_rowLis = new OnRowChangedListener() {
@Override
public void onRowChanged(int newRowIndex) {
// Do nothing
}
};
_selModeLis = new OnSelectionChangedListener() {
@Override
public void onSelectionChanged(boolean active, int selStart, int selEnd) {
// TODO: Implement this method
if (active)
_clipboardPanel.show();
else
_clipboardPanel.hide();
}
};
resetView();
_clipboardPanel = new ClipboardPanel(this);
_autoCompletePanel = new AutoCompletePanel(this);
//TODO find out if this function works
//setScrollContainer(true);
invalidate();
}
/**
* Copies the selected text to the clipboard.
* <p>
* Does nothing if not in select mode.
*/
public void copy(ClipboardManager cb) {
//TODO catch OutOfMemoryError
if (_isInSelectionMode &&
_selectionAnchor < _selectionEdge) {
CharSequence contents = _hDoc.subSequence(_selectionAnchor,
_selectionEdge - _selectionAnchor);
cb.setText(contents);
}
}
public static <T extends Model> void copyLink(Activity ctx, T model) {
if (model.getLastSyncTime().getTime() == 0) {
ToastUtils.makeToast(R.string.cannot_get_link_of_not_synced_item);
return;
}
ClipboardManager clipboardManager = (ClipboardManager) ctx.getSystemService(Context.CLIPBOARD_SERVICE);
clipboardManager.setText(null);
}
public static void copyText(Context context, String content) {
ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
if (!TextUtils.isEmpty(content)) {
cmb.setText(content); //将内容放入粘贴管理器,在别的地方长按选择"粘贴"即可
CharSequence text = cmb.getText();
}
}
private void initView() {
_fieldController = this.new TextFieldController();
_clipboardManager = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
_brush = new Paint();
_brush.setAntiAlias(true);
_brush.setTextSize(BASE_TEXT_SIZE_PIXELS);
_brushLine = new Paint();
_brushLine.setAntiAlias(true);
_brushLine.setTextSize(BASE_TEXT_SIZE_PIXELS);
//setBackgroundColor(_colorScheme.getColor(Colorable.BACKGROUND));
setLongClickable(true);
setFocusableInTouchMode(true);
setHapticFeedbackEnabled(true);
_rowLis = new OnRowChangedListener() {
@Override
public void onRowChanged(int newRowIndex) {
// Do nothing
}
};
_selModeLis = new OnSelectionChangedListener() {
@Override
public void onSelectionChanged(boolean active, int selStart, int selEnd) {
// TODO: Implement this method
if (active)
_clipboardPanel.show();
else
_clipboardPanel.hide();
}
};
resetView();
_clipboardPanel = new ClipboardPanel(this);
_autoCompletePanel = new AutoCompletePanel(this);
//TODO find out if this function works
//setScrollContainer(true);
invalidate();
}
/**
* Copies the selected text to the clipboard.
* <p>
* Does nothing if not in select mode.
*/
public void copy(ClipboardManager cb) {
//TODO catch OutOfMemoryError
if (_isInSelectionMode &&
_selectionAnchor < _selectionEdge) {
CharSequence contents = _hDoc.subSequence(_selectionAnchor,
_selectionEdge - _selectionAnchor);
cb.setText(contents);
}
}
@SuppressWarnings("deprecation")
public final static void copy2ClipBoard(Context context, String src) {
final ClipboardManager clipBoard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
clipBoard.setText(src);
Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
long[] pattern = {30, 0, 0, 20}; // 根据指定的模式进行震动
vibrator.vibrate(pattern, -1);
}
public void scriptErrorCallback(final String scriptName, final Throwable t) {
this.runOnUiThread(new Runnable() {
public void run() {
final StringWriter strWriter = new StringWriter();
PrintWriter pWriter = new PrintWriter(strWriter);
pWriter.println("Error occurred in script: " + scriptName);
if (t instanceof RhinoException) {
String lineSource = ((RhinoException) t).lineSource();
if (lineSource != null)
pWriter.println(lineSource);
}
t.printStackTrace(pWriter);
new AlertDialog.Builder(MainActivity.this)
.setTitle(R.string.script_execution_error)
.setMessage(strWriter.toString())
.setPositiveButton(android.R.string.ok, null)
.setNeutralButton(android.R.string.copy,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface aDialog, int button) {
ClipboardManager mgr = (ClipboardManager) MainActivity.this
.getSystemService(CLIPBOARD_SERVICE);
mgr.setText(strWriter.toString());
}
}).show();
}
});
}
public void onClick(View v) {
AlbumCommentDetailActivity.this.dismissPopupWin();
if (AlbumCommentDetailActivity.this.mClipBoard == null) {
AlbumCommentDetailActivity.this.mClipBoard = (ClipboardManager) BaseApplication.getInstance().getSystemService("clipboard");
}
AlbumCommentDetailActivity.this.mClipBoard.setText(replyItem.content);
LogInfo.log("fornia", "复制评论到剪贴板:" + replyItem.content);
ToastUtils.showToast(BaseApplication.getInstance().getResources().getString(R.string.detail_comment_toast_copy_play));
}
public void reportError(final Throwable t, final int messageId, final String extraData) {
this.runOnUiThread(new Runnable() {
public void run() {
final StringWriter strWriter = new StringWriter();
PrintWriter pWriter = new PrintWriter(strWriter);
t.printStackTrace(pWriter);
final String msg;
if (extraData != null) {
msg = extraData + "\n" + strWriter.toString();
} else {
msg = strWriter.toString();
}
new AlertDialog.Builder(MainActivity.this)
.setTitle(messageId)
.setMessage(msg)
.setPositiveButton(android.R.string.ok, null)
.setNeutralButton(android.R.string.copy,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface aDialog, int button) {
ClipboardManager mgr = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
mgr.setText(msg);
}
}).
show();
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item_like:
if (isLiked) {
item.setIcon(R.drawable.ic_notlike);
daoManager.deleteByGuid(guid);
isLiked = false;
SnackBarUtils.show(((ViewGroup) findViewById(android.R.id.content)).getChildAt(0), "成功从收藏中移除");
} else {
item.setIcon(R.drawable.ic_like);
LikeBean bean = new LikeBean();
bean.setId(null);
bean.setGuid(guid);
bean.setImageUrl(imageUrl);
bean.setTitle(title);
bean.setUrl(url);
bean.setType(type);
bean.setTime(System.currentTimeMillis());
daoManager.insert(bean);
isLiked = true;
SnackBarUtils.show(((ViewGroup) findViewById(android.R.id.content)).getChildAt(0), "成功添加到收藏");
}
break;
case R.id.item_copy:
ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
cm.setText(url);
SnackBarUtils.show(webView, R.string.copy_msg, this);
break;
case R.id.item_browser:
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
break;
}
return super.onOptionsItemSelected(item);
}
public void onPrepareDialog(int dialogId, Dialog dialog) {
switch (dialogId) {
case DIALOG_MANAGE_PATCH:
case DIALOG_MANAGE_PATCH_CURRENTLY_ENABLED:
case DIALOG_MANAGE_PATCH_CURRENTLY_DISABLED:
if (selectedPatchItem == null) {
break;
}
AlertDialog aDialog = (AlertDialog) dialog;
aDialog.setTitle(selectedPatchItem.toString(getResources()));
break;
case DIALOG_PATCH_INFO:
if (selectedPatchItem == null) {
break;
}
preparePatchInfo((AlertDialog) dialog, selectedPatchItem);
break;
case DIALOG_IMPORT_FROM_CLIPBOARD_CODE:
AlertDialog bDialog = (AlertDialog) dialog;
android.text.ClipboardManager cmgr = (android.text.ClipboardManager) this.getSystemService(Context.CLIPBOARD_SERVICE);
CharSequence cSequence = cmgr.getText();
((EditText) bDialog.findViewById(20130805)).setText(cSequence);
break;
case DIALOG_IMPORT_FROM_INTENT:
AlertDialog cDialog = (AlertDialog) dialog;
cDialog.setTitle(getIntent().getData().toString());
break;
default:
super.onPrepareDialog(dialogId, dialog);
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// get the clipboard system service
ClipboardManager clipboardManager = (ClipboardManager) this.getSystemService(CLIPBOARD_SERVICE);
// get the text to copy into the clipboard
Intent intent = getIntent();
CharSequence text = intent.getCharSequenceExtra(Intent.EXTRA_TEXT);
// and put the text the clipboard
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
// API level >= 11 -> modern Clipboard
ClipData clip = ClipData.newPlainText("Synox was here", text);
((android.content.ClipboardManager)clipboardManager).setPrimaryClip(clip);
} else {
// API level >= 11 -> legacy Clipboard
clipboardManager.setText(text);
}
// alert the user that the text is in the clipboard and we're done
Toast.makeText(this, R.string.clipboard_text_copied, Toast.LENGTH_SHORT).show();
finish();
}
/**
* 实现文本复制功能
* add by wangqianzhou
*
* @param content
*/
public static void copy(Context context, String content) {
// 得到剪贴板管理器
ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
if (!StringUtils.isEmptyOrNullOrNullStr(content)) {
cmb.setText(content.trim());
}
}
/**
* 实现文本复制功能
*
* @param content
*/
@SuppressWarnings("deprecation")
public static void copy(Context context, @NonNull String content) {
// 得到剪贴板管理器
ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
cmb.setText(content.trim());
}
private void handleCopyMessage(final Set<DcMsg> dcMsgsSet) {
List<DcMsg> dcMsgsList = new LinkedList<>(dcMsgsSet);
Collections.sort(dcMsgsList, (lhs, rhs) -> Long.compare(lhs.getDateReceived(), rhs.getDateReceived()));
StringBuilder result = new StringBuilder();
DcMsg prevMsg = new DcMsg(dcContext, DcMsg.DC_MSG_TEXT);
for (DcMsg msg : dcMsgsList) {
if (result.length() > 0) {
result.append("\n\n");
}
if (msg.getFromId() != prevMsg.getFromId()) {
DcContact contact = dcContext.getContact(msg.getFromId());
result.append(contact.getDisplayName()).append(":\n");
}
if(msg.getType() == DcMsg.DC_MSG_TEXT) {
result.append(msg.getText());
} else {
result.append(msg.getSummarytext(10000000));
}
prevMsg = msg;
}
if (result.length() > 0) {
try {
ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setText(result.toString());
Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.copied_to_clipboard), Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void clipboard(TextView tv) {
// which view are we copying to the clipboard?
int which;
switch (tv.getId()) {
case txt_request_url: // the url field
which = code_snippet;
break;
case txt_response_body: // the response body
which = raw_object;
break;
default:
which = UNSET; // don't assign a prefix
}
// if we know which view we're copying, prefix it with useful info
String what = which == UNSET ? "" : getString(which) + " ";
// concat the clipboard data to this String
what += getString(clippy);
// inform the user that data was added to the clipboard
Toast.makeText(
getActivity(),
what,
Toast.LENGTH_SHORT
).show();
// depending on our API, do it one way or another...
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
// old way
ClipboardManager clipboardManager = (ClipboardManager)
getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
clipboardManager.setText(tv.getText());
} else {
clipboard11(tv);
}
}
@TargetApi(11)
private void clipboard11(TextView tv) {
android.content.ClipboardManager clipboardManager =
(android.content.ClipboardManager) getActivity()
.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clipData = ClipData.newPlainText("RESTSnippets", tv.getText());
clipboardManager.setPrimaryClip(clipData);
}
private void clipboard(TextView tv) {
int which;
switch (tv.getId()) {
case txt_request_url:
which = req_url;
break;
case txt_response_headers:
which = response_headers;
break;
case txt_response_body:
which = response_body;
break;
default:
which = UNSET;
}
String what = which == UNSET ? "" : getString(which) + " ";
what += getString(clippy);
Toast.makeText(getActivity(), what, Toast.LENGTH_SHORT).show();
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
// old way
ClipboardManager clipboardManager = (ClipboardManager)
getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
clipboardManager.setText(tv.getText());
} else {
clipboard11(tv);
}
}
@TargetApi(11)
private void clipboard11(TextView tv) {
android.content.ClipboardManager clipboardManager =
(android.content.ClipboardManager) getActivity()
.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clipData = ClipData.newPlainText("OneNote", tv.getText());
clipboardManager.setPrimaryClip(clipData);
}
private void handleCopyMessage(final Set<MessageRecord> messageRecords) {
List<MessageRecord> messageList = new LinkedList<>(messageRecords);
Collections.sort(messageList, new Comparator<MessageRecord>() {
@Override
public int compare(MessageRecord lhs, MessageRecord rhs) {
if (lhs.getDateReceived() < rhs.getDateReceived()) return -1;
else if (lhs.getDateReceived() == rhs.getDateReceived()) return 0;
else return 1;
}
});
StringBuilder bodyBuilder = new StringBuilder();
ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
boolean first = true;
for (MessageRecord messageRecord : messageList) {
String body = messageRecord.getDisplayBody().toString();
if (body != null) {
if (!first) bodyBuilder.append('\n');
bodyBuilder.append(body);
first = false;
}
}
String result = bodyBuilder.toString();
if (!TextUtils.isEmpty(result))
clipboard.setText(result);
}
@Override
public void onClick(View v) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
// Should always be true, because we grey out the clipboard button in onResume() if it's empty
if (clipboard.hasText()) {
launchSearch(clipboard.getText().toString());
}
}