Question

I have a Text Field and a Button. I'd make it so as soon as the button is pressed the text of the Text Field to be copied. How can this be done? As I search it (How to copy text programmatically in my Android app?), I read about a ClipboardManager method but rumours say it is also deprecated. Should I avoid it? Thanks

Was it helpful?

Solution

Honeycomb deprecated android.text.ClipboardManager and introduced android.content.ClipboardManager.

You should check whether android.os.Build.VERSION.SDK_INT is at least android.os.Build.VERSION_CODES.HONEYCOMB and therefore use one or the other.

    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB)
    {
        // Old clibpoard
        android.text.ClipboardManager clipboard = (android.text.ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
        clipboard.setText("the text");
    } 
    else
    {
        android.content.ClipboardManager clipboard = (android.content.ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
        android.content.ClipData clipData = android.content.ClipData.newPlainText("PlainText", "the text");
        clipboard.setPrimaryClip(clipData);
    }       

OTHER TIPS

Try the answer in this link..It says

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

Copy/Paste Offical Tutoiral Check it out

Relative Code :

ClipboardManager clipboard = (ClipboardManager)
    getSystemService(Context.CLIPBOARD_SERVICE);
Copy the data to a new ClipData object:
For text

// Creates a new text clip to put on the clipboard
 ClipData clip = ClipData.newPlainText("simple text","Hello, World!");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top