简体   繁体   中英

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM