Java Code Examples for android.text.ClipboardManager#setText()

The following examples show how to use android.text.ClipboardManager#setText() . 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 File: ChatFragment.java    From jitsi-android with 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 2
Source File: SearchResultFragment.java    From MCPDict with 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 3
Source File: FreeScrollingTextField.java    From CodeEditor with 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 4
Source File: ConversationFragment.java    From Silence with 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 5
Source File: SnippetDetailFragment.java    From Android-REST-API-Explorer with 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 6
Source File: ClipboardHelper.java    From GankMeizhi with 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 7
Source File: MicroBlogShareClickListener.java    From YiBo with Apache License 2.0 5 votes vote down vote up
@Override
public void onClick(View v) {
	if (status == null || status.getStatusId() == null) {
		return;
	}

	Intent intent = new Intent(Intent.ACTION_SEND);
	
	if (EntityUtil.hasPicture(status)) {
		intent.setType("image/*");
		
		String imagePath = EntityUtil.getMaxLocalCachedPicture(status);
		if (StringUtil.isNotEmpty(imagePath)) {
			Uri uri = Uri.fromFile(new File(imagePath));
		    intent.putExtra(Intent.EXTRA_STREAM, uri);
		} else {
			intent.setType("text/plain");
			Toast.makeText(context, context.getString(R.string.msg_blog_share_picture), Toast.LENGTH_LONG).show();
		}
	} else {
		intent.setType("text/plain");
	}
	
	ClipboardManager clip = (ClipboardManager)context
           .getSystemService(Context.CLIPBOARD_SERVICE);
	String statusText = extraStatus(context, status);
	clip.setText(statusText);
	
	intent.putExtra(Intent.EXTRA_TEXT, statusText);				
	intent.putExtra(Intent.EXTRA_SUBJECT, context.getString(R.string.msg_extra_subject));
	context.startActivity(intent);
}
 
Example 8
Source File: CopyToClipboardActivity.java    From Cirrus_depricated with 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 9
Source File: WebActivity.java    From Ency with 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 10
Source File: ScreenDimensionsFragment.java    From java-android-developertools with Apache License 2.0 5 votes vote down vote up
protected void copyscreenDimensions() {
    ClipboardManager clipboardManager = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
    if (clipboardManager != null) {
        clipboardManager.setText(screenDimensions);
        Toast.makeText(getActivity().getApplicationContext(), "Screen dimensions copied to clipboard.", Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(getActivity().getApplicationContext(), "Unable to get clipboard manager.", Toast.LENGTH_LONG).show();
    }
}
 
Example 11
Source File: ModelHelper.java    From OmniList with 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 File: ConversationFragment.java    From mollyim-android with 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 13
Source File: AboutAty.java    From Huochexing12306 with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
private void copyToClipboard(CharSequence content){
	ClipboardManager cm = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
	cm.setText(content);
	showMsg("信息已复制到剪贴版"+SF.SUCCESS);
}
 
Example 14
Source File: WSActivity.java    From AndroidWebServ with Apache License 2.0 4 votes vote down vote up
private void copy2Clipboard(String text) {
    ClipboardManager cm = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
    cm.setText(text);
}
 
Example 15
Source File: ActivityCrashReport.java    From ViewDebugHelper with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * copy plain text to clip board<br/>
 * 复制文本到剪切板<br/>
 */
public static void copyToClipBoard(Context context, CharSequence text) {
    ClipboardManager clipboardManager = (ClipboardManager) context
            .getSystemService(Context.CLIPBOARD_SERVICE);
    clipboardManager.setText(text);
}
 
Example 16
Source File: SnippetDetailFragment.java    From android-java-snippets-rest-sample with MIT License 4 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 = req_url;
            break;

        case txt_response_headers: // the display headers
            which = response_headers;
            break;

        case txt_response_body: // the response body
            which = response_body;
            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 17
Source File: IOHelper.java    From fanfouapp-opensource with Apache License 2.0 4 votes vote down vote up
public static void copyToClipBoard(final Context context,
        final String content) {
    final ClipboardManager cm = (ClipboardManager) context
            .getSystemService(Context.CLIPBOARD_SERVICE);
    cm.setText(content);
}
 
Example 18
Source File: CaptureActivity.java    From android-apps with MIT License 4 votes vote down vote up
private void handleDecodeInternally(Result rawResult, ResultHandler resultHandler, Bitmap barcode) {
  statusView.setVisibility(View.GONE);
  viewfinderView.setVisibility(View.GONE);
  resultView.setVisibility(View.VISIBLE);

  ImageView barcodeImageView = (ImageView) findViewById(R.id.barcode_image_view);
  if (barcode == null) {
    barcodeImageView.setImageBitmap(BitmapFactory.decodeResource(getResources(),
        R.drawable.launcher_icon));
  } else {
    barcodeImageView.setImageBitmap(barcode);
  }

  TextView formatTextView = (TextView) findViewById(R.id.format_text_view);
  formatTextView.setText(rawResult.getBarcodeFormat().toString());

  TextView typeTextView = (TextView) findViewById(R.id.type_text_view);
  typeTextView.setText(resultHandler.getType().toString());

  DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
  String formattedTime = formatter.format(new Date(rawResult.getTimestamp()));
  TextView timeTextView = (TextView) findViewById(R.id.time_text_view);
  timeTextView.setText(formattedTime);


  TextView metaTextView = (TextView) findViewById(R.id.meta_text_view);
  View metaTextViewLabel = findViewById(R.id.meta_text_view_label);
  metaTextView.setVisibility(View.GONE);
  metaTextViewLabel.setVisibility(View.GONE);
  Map<ResultMetadataType,Object> metadata = rawResult.getResultMetadata();
  if (metadata != null) {
    StringBuilder metadataText = new StringBuilder(20);
    for (Map.Entry<ResultMetadataType,Object> entry : metadata.entrySet()) {
      if (DISPLAYABLE_METADATA_TYPES.contains(entry.getKey())) {
        metadataText.append(entry.getValue()).append('\n');
      }
    }
    if (metadataText.length() > 0) {
      metadataText.setLength(metadataText.length() - 1);
      metaTextView.setText(metadataText);
      metaTextView.setVisibility(View.VISIBLE);
      metaTextViewLabel.setVisibility(View.VISIBLE);
    }
  }

  TextView contentsTextView = (TextView) findViewById(R.id.contents_text_view);
  CharSequence displayContents = resultHandler.getDisplayContents();
  contentsTextView.setText(displayContents);
  // Crudely scale betweeen 22 and 32 -- bigger font for shorter text
  int scaledSize = Math.max(22, 32 - displayContents.length() / 4);
  contentsTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, scaledSize);

  TextView supplementTextView = (TextView) findViewById(R.id.contents_supplement_text_view);
  supplementTextView.setText("");
  supplementTextView.setOnClickListener(null);
  if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean(
      PreferencesActivity.KEY_SUPPLEMENTAL, true)) {
    SupplementalInfoRetriever.maybeInvokeRetrieval(supplementTextView,
                                                   resultHandler.getResult(),
                                                   handler,
                                                   historyManager,
                                                   this);
  }

  int buttonCount = resultHandler.getButtonCount();
  ViewGroup buttonView = (ViewGroup) findViewById(R.id.result_button_view);
  buttonView.requestFocus();
  for (int x = 0; x < ResultHandler.MAX_BUTTON_COUNT; x++) {
    TextView button = (TextView) buttonView.getChildAt(x);
    if (x < buttonCount) {
      button.setVisibility(View.VISIBLE);
      button.setText(resultHandler.getButtonText(x));
      button.setOnClickListener(new ResultButtonListener(resultHandler, x));
    } else {
      button.setVisibility(View.GONE);
    }
  }

  if (copyToClipboard && !resultHandler.areContentsSecure()) {
    ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
    clipboard.setText(displayContents);
  }
}
 
Example 19
Source File: ModelHelper.java    From OmniList with GNU Affero General Public License v3.0 4 votes vote down vote up
public static void copyToClipboard(Activity ctx, String content) {
    ClipboardManager clipboardManager = (ClipboardManager) ctx.getSystemService(Context.CLIPBOARD_SERVICE);
    clipboardManager.setText(content);
}
 
Example 20
Source File: CaptureActivity.java    From reacteu-app with MIT License 4 votes vote down vote up
private void handleDecodeInternally(Result rawResult, ResultHandler resultHandler, Bitmap barcode) {
  statusView.setVisibility(View.GONE);
  viewfinderView.setVisibility(View.GONE);
  resultView.setVisibility(View.VISIBLE);

  ImageView barcodeImageView = (ImageView) findViewById(fakeR.getId("id", "barcode_image_view"));
  if (barcode == null) {
    barcodeImageView.setImageBitmap(BitmapFactory.decodeResource(getResources(),
        fakeR.getId("drawable", "launcher_icon")));
  } else {
    barcodeImageView.setImageBitmap(barcode);
  }

  TextView formatTextView = (TextView) findViewById(fakeR.getId("id", "format_text_view"));
  formatTextView.setText(rawResult.getBarcodeFormat().toString());

  TextView typeTextView = (TextView) findViewById(fakeR.getId("id", "type_text_view"));
  typeTextView.setText(resultHandler.getType().toString());

  DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
  String formattedTime = formatter.format(new Date(rawResult.getTimestamp()));
  TextView timeTextView = (TextView) findViewById(fakeR.getId("id", "time_text_view"));
  timeTextView.setText(formattedTime);


  TextView metaTextView = (TextView) findViewById(fakeR.getId("id", "meta_text_view"));
  View metaTextViewLabel = findViewById(fakeR.getId("id", "meta_text_view_label"));
  metaTextView.setVisibility(View.GONE);
  metaTextViewLabel.setVisibility(View.GONE);
  Map<ResultMetadataType,Object> metadata = rawResult.getResultMetadata();
  if (metadata != null) {
    StringBuilder metadataText = new StringBuilder(20);
    for (Map.Entry<ResultMetadataType,Object> entry : metadata.entrySet()) {
      if (DISPLAYABLE_METADATA_TYPES.contains(entry.getKey())) {
        metadataText.append(entry.getValue()).append('\n');
      }
    }
    if (metadataText.length() > 0) {
      metadataText.setLength(metadataText.length() - 1);
      metaTextView.setText(metadataText);
      metaTextView.setVisibility(View.VISIBLE);
      metaTextViewLabel.setVisibility(View.VISIBLE);
    }
  }

  TextView contentsTextView = (TextView) findViewById(fakeR.getId("id", "contents_text_view"));
  CharSequence displayContents = resultHandler.getDisplayContents();
  contentsTextView.setText(displayContents);
  // Crudely scale betweeen 22 and 32 -- bigger font for shorter text
  int scaledSize = Math.max(22, 32 - displayContents.length() / 4);
  contentsTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, scaledSize);

  TextView supplementTextView = (TextView) findViewById(fakeR.getId("id", "contents_supplement_text_view"));
  supplementTextView.setText("");
  supplementTextView.setOnClickListener(null);
  if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean(
      PreferencesActivity.KEY_SUPPLEMENTAL, true)) {
    SupplementalInfoRetriever.maybeInvokeRetrieval(supplementTextView,
                                                   resultHandler.getResult(),
                                                   historyManager,
                                                   this);
  }

  int buttonCount = resultHandler.getButtonCount();
  ViewGroup buttonView = (ViewGroup) findViewById(fakeR.getId("id", "result_button_view"));
  buttonView.requestFocus();
  for (int x = 0; x < ResultHandler.MAX_BUTTON_COUNT; x++) {
    TextView button = (TextView) buttonView.getChildAt(x);
    if (x < buttonCount) {
      button.setVisibility(View.VISIBLE);
      button.setText(resultHandler.getButtonText(x));
      button.setOnClickListener(new ResultButtonListener(resultHandler, x));
    } else {
      button.setVisibility(View.GONE);
    }
  }

  if (copyToClipboard && !resultHandler.areContentsSecure()) {
    ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
    if (displayContents != null) {
      clipboard.setText(displayContents);
    }
  }
}