android.text.ClipboardManager Java Examples

The following examples show how to use android.text.ClipboardManager. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: FanXin-based-HuanXin   Author: dhcai   File: PasteEditText.java    License: GNU General Public License v2.0 6 votes vote down vote up
@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);
    }
 
Example #2
Source Project: school_shop   Author: Owater   File: PasteEditText.java    License: MIT License 6 votes vote down vote up
@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);
    }
 
Example #3
Source Project: aedict   Author: mvysny   File: CopyActivity.java    License: GNU General Public License v3.0 6 votes vote down vote up
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);
			}
		});
	}
}
 
Example #4
Source Project: MCPDict   Author: MaigoAkisame   File: SearchResultFragment.java    License: MIT License 6 votes vote down vote up
@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;
    }
}
 
Example #5
Source Project: MCPELauncher   Author: zhuowei   File: ManageScriptsActivity.java    License: Apache License 2.0 6 votes vote down vote up
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();
		}
	});
}
 
Example #6
Source Project: libpastelog   Author: signalapp   File: SubmitLogFragment.java    License: GNU General Public License v3.0 6 votes vote down vote up
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;
}
 
Example #7
Source Project: jitsi-android   Author: jitsi   File: ChatFragment.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * {@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);
}
 
Example #8
Source Project: mollyim-android   Author: mollyim   File: ConversationFragment.java    License: GNU General Public License v3.0 5 votes vote down vote up
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);
}
 
Example #9
Source Project: CodeEditor   Author: TIIEHenry   File: FreeScrollingTextField.java    License: Apache License 2.0 5 votes vote down vote up
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();
}
 
Example #10
Source Project: CodeEditor   Author: TIIEHenry   File: FreeScrollingTextField.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example #11
Source Project: OmniList   Author: Shouheng88   File: ModelHelper.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
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);
}
 
Example #12
Source Project: WechatHook-Dusan   Author: duqian291902259   File: UIUtil.java    License: Apache License 2.0 5 votes vote down vote up
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();
    }
}
 
Example #13
Source Project: CodeEditor   Author: TIIEHenry   File: FreeScrollingTextField.java    License: Apache License 2.0 5 votes vote down vote up
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();
}
 
Example #14
Source Project: CodeEditor   Author: TIIEHenry   File: FreeScrollingTextField.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example #15
Source Project: Ticket-Analysis   Author: xiaolongonly   File: Utils.java    License: MIT License 5 votes vote down vote up
@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);
}
 
Example #16
Source Project: MCPELauncher   Author: zhuowei   File: MainActivity.java    License: Apache License 2.0 5 votes vote down vote up
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();
		}
	});
}
 
Example #17
Source Project: letv   Author: JackChan1999   File: AlbumCommentDetailActivity.java    License: Apache License 2.0 5 votes vote down vote up
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));
}
 
Example #18
Source Project: MCPELauncher   Author: zhuowei   File: MainActivity.java    License: Apache License 2.0 5 votes vote down vote up
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();
		}
	});
}
 
Example #19
Source Project: Ency   Author: Jerry-1123   File: WebActivity.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #20
Source Project: MCPELauncher   Author: zhuowei   File: ManageScriptsActivity.java    License: Apache License 2.0 5 votes vote down vote up
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);
	}
}
 
Example #21
Source Project: Cirrus_depricated   Author: skymania   File: CopyToClipboardActivity.java    License: GNU General Public License v2.0 5 votes vote down vote up
@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();
}
 
Example #22
Source Project: BigApp_Discuz_Android   Author: BigAppOS   File: ClipboardUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
     * 实现文本复制功能
     * 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());
        }
    }
 
Example #23
Source Project: GankMeizhi   Author: AlwaysTyping   File: ClipboardHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 实现文本复制功能
 *
 * @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());
}
 
Example #24
Source Project: deltachat-android   Author: deltachat   File: ConversationFragment.java    License: GNU General Public License v3.0 5 votes vote down vote up
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();
        }
    }
}
 
Example #25
Source Project: android-java-snippets-sample   Author: microsoftgraph   File: SnippetDetailFragment.java    License: MIT License 5 votes vote down vote up
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);
    }
}
 
Example #26
Source Project: android-java-snippets-sample   Author: microsoftgraph   File: SnippetDetailFragment.java    License: MIT License 5 votes vote down vote up
@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);
}
 
Example #27
Source Project: Android-REST-API-Explorer   Author: OneNoteDev   File: SnippetDetailFragment.java    License: MIT License 5 votes vote down vote up
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);
    }
}
 
Example #28
Source Project: Android-REST-API-Explorer   Author: OneNoteDev   File: SnippetDetailFragment.java    License: MIT License 5 votes vote down vote up
@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);
}
 
Example #29
Source Project: Silence   Author: SilenceIM   File: ConversationFragment.java    License: GNU General Public License v3.0 5 votes vote down vote up
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);
}
 
Example #30
Source Project: reacteu-app   Author: Thinkmill   File: ShareActivity.java    License: MIT License 5 votes vote down vote up
@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());
  }
}