Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Copying a text to the clipboard for API < 11

I have a problem with copying a text to the clipboard. I try to copy like this:

android.content.ClipboardManager clipboard = ( android.content.ClipboardManager ) getSystemService(Context.CLIPBOARD_SERVICE ); 
android.content.ClipData clip = android.content.ClipData.newPlainText( "text label", "text to clip" );
clipboard.setPrimaryClip( clip );

But problem is in the compiler which throws:

Call requires API level 11 (current min is 7): android.content.ClipboardManager#setPrimaryClip line 245 Android Lint Problem.

How I can copy a text to the clipboard on android API < 11? If i try to check API version of android before copying - my code even doesn't compile. Maybe someone knows an answer to this question?

like image 451
JavaRunner Avatar asked Oct 11 '12 19:10

JavaRunner


1 Answers

Reference : How to copy text programmatically in my Android app

int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
    android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    clipboard.setText("text to clip");
} else {
    android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); 
    android.content.ClipData clip = android.content.ClipData.newPlainText("text label","text to clip");
    clipboard.setPrimaryClip(clip);
}

Added: you may have to clean and build your project :)

like image 161
Vishal Vyas Avatar answered Nov 10 '22 00:11

Vishal Vyas