Domanda

I'm looking for a way to copy and paste from the clipboard throughout every version of Android. Right now, I'm only aware of how to do this in APIs 11+.

copy.setOnLongClickListener(new View.OnLongClickListener()
    {
        @SuppressLint({ "NewApi", "NewApi" })
        @Override
        public boolean onLongClick(View v)
        {
            clipboard = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
            clipdata = ClipData.newPlainText("simple text", copy.getText().toString());
            clipboard.setPrimaryClip(clipdata);
            Toast.makeText(getApplicationContext(), "Copied to clipboard..", Toast.LENGTH_SHORT).show();
            return true;
        }
    });

    paste.setOnLongClickListener(new View.OnLongClickListener()
    {
        @SuppressLint({ "NewApi", "NewApi" })
        @Override
        public boolean onLongClick(View v)
        {
            clipboard = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
            String pasteData = "";
            item = clipboard.getPrimaryClip().getItemAt(0);
            pasteData = item.getText().toString();
            paste.setText(pasteData);
            Toast.makeText(getApplicationContext(), "Pasted", Toast.LENGTH_SHORT).show();
            return true;
        }
    });

I'll appreciate any help, thanks.

È stato utile?

Soluzione

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

Altri suggerimenti

ClipboardManager wasn't added in v11, the documentation is wrong. It was redesigned in v11. You can still see the old deprecated functions in the documentation. Do a version check and use the old functions on old versions and the new ones on new versions. See getText, hasText, and setText of ClipboardManager.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top