As of Android Oreo, the support library only goes down to API 14. Most newer apps probably also have a min API of 14, and thus don't need to worry about the issues with API 11 mentioned in some of the other answers. A lot of the code can be cleaned up. (But see my edit history if you are still supporting lower versions.)
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("label", selectedText);
if (clipboard == null || clip == null) return;
clipboard.setPrimaryClip(clip);
I'm adding this code as a bonus, because copy/paste is usually done in pairs.
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
try {
CharSequence text = clipboard.getPrimaryClip().getItemAt(0).getText();
} catch (Exception e) {
return;
}
android.content.ClipboardManager
version rather than the old android.text.ClipboardManager
. Same for ClipData
.context.getSystemService()
.null
. You can check each one if you find that way more readable.