I wrote a code which copies an answer in calculator to clipboard, then calculator is closed and another window is opened. The answer should be pasted here using code:
textOut2= (TextView) findViewById(R.id.etInput1);
final ClipboardManager clipBoard= (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
textOut2.setText(clipBoard.getText());
but it never works. WHere could be a mistake? p.s. I know what text is copied because I can paste using long press but I want to do it automaticaly. And is it possible to give a specific name for a copied text? As it would make it easier to paste words as I have a lot of different TextView's
public CharSequence getText () Since: API Level 11 This method is deprecated. Use getPrimaryClip() instead. This retrieves the primary clip and tries to coerce it to a string.
String textToPaste = null;
ClipboardManager clipboard = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
if (clipboard.hasPrimaryClip()) {
ClipData clip = clipboard.getPrimaryClip();
// if you need text data only, use:
if (clip.getDescription().hasMimeType(MIMETYPE_TEXT_PLAIN))
// WARNING: The item could cantain URI that points to the text data.
// In this case the getText() returns null and this code fails!
textToPaste = clip.getItemAt(0).getText().toString();
// or you may coerce the data to the text representation:
textToPaste = clip.getItemAt(0).coerceToText(this).toString();
}
if (!TextUtils.isEmpty(textToPaste))
((TextView)findViewById(R.id.etInput1)).setText(textToPaste);
You are allowed to add additional ClipData.Item
items with text via ClipData.addItem()
, but there is no way to discern them.
try this
textOut2= (TextView) findViewById(R.id.etInput1);
final ClipboardManager clipBoard= (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
String temp = new String;
temp = clipBoard.getText().toString();
textOut2.setText(temp);
In Kotlin:
val clipboard = (getSystemService(Context.CLIPBOARD_SERVICE)) as? ClipboardManager
val textToPaste = clipboard?.primaryClip?.getItemAt(0)?.text ?: return
binding.<your EditText camelCase id>.setText(textToPaste)
Inside Fragment: getSystemService() is a method on the Context class and it's necessary to call Context first. It's possible by either using getContext() or alternatively, the getActivity() - Activity is also a Context.
this.activity.getSystemService(...)
this.context.getSystemService(...)
Or:
activity.getSystemService(...)
context.getSystemService(...)
Plus remember about only safe (?.) or non-null asserted (!!.) calls.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With