ixx
ixx

Reputation: 32269

Cross-version (starting api 7 (eclair)) copy paste in Android?

I want to enable copy paste in a TextView.

I found these very nice explanations in Android docs: http://developer.android.com/guide/topics/clipboard/copy-paste.html

But it works only starting at version 11 - honeycomb!

I need something which also works for the majority of users at this point of time, means it has to work also for gingerbread, froyo and eclair.

What do I use?

Upvotes: 1

Views: 853

Answers (2)

cprcrack
cprcrack

Reputation: 19169

These are the completely cross-platform and exception-free ways to copy plain text to clipboard and paste plain text from clipboard in Android:

@SuppressLint("NewApi") @SuppressWarnings("deprecation")
public void copy(String plainText)
{
    if (android.os.Build.VERSION.SDK_INT < 11)
    {
        android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        if (clipboard != null)
        {
            clipboard.setText(plainText);
        }
    }
    else
    {
        android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        if (clipboard != null)
        {
            android.content.ClipData clip = android.content.ClipData.newPlainText("text", plainText);
            clipboard.setPrimaryClip(clip);
        }
    }
}

@SuppressLint("NewApi") @SuppressWarnings("deprecation")
public String paste()
{
    if (android.os.Build.VERSION.SDK_INT < 11)
    {
        android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        if (clipboard != null)
        {
            return (String) clipboard.getText();
        }
    }
    else
    {
        android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        if (clipboard != null && clipboard.getPrimaryClip() != null && clipboard.getPrimaryClip().getItemCount() > 0)
        {
            return (String) clipboard.getPrimaryClip().getItemAt(0).getText();
        }
    }
    return null;
}

Upvotes: 1

CommonsWare
CommonsWare

Reputation: 1007296

Use the ClipboardManager found in the android.text package. They moved it to a different package because they started supporting clipping things other than text, but for backwards compatibility you can still use it under the old name.

You still wind up with stuff like:

    ClipboardManager cm=(ClipboardManager)getSystemService(CLIPBOARD_SERVICE);

    cm.setText("something");

Here is a sample project demonstrating this.

Upvotes: 3

Related Questions