Java – copy clipboard manager that supports old and new versions?

I'm trying to edit text on Android. For another question, the most voting answer provides these lines, but when I use them, I get an error: the class requires API level 11 (currently the minimum is 8):

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

I copied these lines directly from the question Try to import Android content. ClipboardManager; I test importing Android text. ClipboardManager; But it also produces errors For the clipboardmanager type, the setprimaryclip (clipdata) method is undefined, and the warning about clipboardmanager is not recommended

My application supports Android 2.2 (I think API 8). How can I copy text to make it applicable to all versions of Android?

Solution

Try 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");
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>