10

I'm trying to copy text programatically on android, the most voted answer on another question provided these lines but when using them I get error: Class requires API level 11 (current min is 8):

ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("label", "Text to copy");
clipboard.setPrimaryClip(clip);

I copied the lines directly from the question. After trying with import android.content.ClipboardManager; I tested import android.text.ClipboardManager; and but it produced an error too The method setPrimaryClip(ClipData) is undefined for the type ClipboardManager plus warnings about ClipboardManager being deprecated.

My app that supports Android 2.2 (API 8 I think) onwards, how can I copy text so it works on all versions of android?

Jared Burrows
  • 54,294
  • 25
  • 151
  • 185
lisovaccaro
  • 32,502
  • 98
  • 258
  • 410

1 Answers1

30

Try to use something like the following:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    final android.content.ClipboardManager clipboardManager = (android.content.ClipboardManager) context
            .getSystemService(Context.CLIPBOARD_SERVICE);
    final android.content.ClipData clipData = android.content.ClipData
            .newPlainText("text label", "text to clip");
    clipboardManager.setPrimaryClip(clipData);
} else {
    final android.text.ClipboardManager clipboardManager = (android.text.ClipboardManager) context
            .getSystemService(Context.CLIPBOARD_SERVICE);
    clipboardManager.setText("text to clip");
}
Jared Burrows
  • 54,294
  • 25
  • 151
  • 185
Raj
  • 1,843
  • 2
  • 21
  • 47