Search code examples
androidtextviewdeprecatedandroid-appcompatclipboardmanager

Android: Clipboard issue


I am having a very annoying problem. I'm developing an app and now I need to get the text that is in a TextView and pass it to the clipboard. In other words, i need to copy the text.

android:textIsSelectable = "true" works on newe versions, but i need this app to run on API10 ( 2.3.3 )

I tried this:

    import android.text.ClipboardManager;
    [ . . . ]
    private CharSequence code;
    [ . . . ]
    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {

        codeTextView.setOnLongClickListener(new OnLongClickListener() {

            public boolean onLongClick(View v) {
                code = codeTextView.getText();
                ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(CLIPBOARD_SERVICE); 
                clipboard.setText(code);
                Log.i(TAG, "COPIED! ->" + (clipboard.getText()));

                return false;
            }
        });

Okay. The problem is: CLIPBOARD_SERVICE has an error: CLIPBOARD_SERVICE cannot be resolved to a variable

How to get rid of this? I mean, if I try and remove this, it seems that the method "getSystemService" doesn't exist. What's going on?

Notes:

  • I'm using appcompat_v7
  • Running normally on Honeycomb and above
  • The version checking works fine

Solution

  • Simple:

    Use Context.CLIPBOARD_SERVICE:

    ClipboardManager clipboard = (android.text.ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE); 
    

    CLIPBOARD_SERVICE is a static field of Context. I guess the code was used in a subclass of Context in the place you got it from, and as yours is no subclass of Context, you have to put the Context before.