lisovaccaro
lisovaccaro

Reputation: 33966

Copy with clipboard manager that supports old and new android versions?

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?

Upvotes: 10

Views: 9313

Answers (1)

Raj
Raj

Reputation: 1872

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");
}

Upvotes: 31

Related Questions