2

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
igorfeiden
  • 177
  • 7

1 Answers1

3

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.

FD_
  • 12,947
  • 4
  • 35
  • 62
  • Thanks. I got rid from the error. But then, another one appeared: `The method getSystemService(String) is undefined for the type new View.OnLongClickListener(){}` – igorfeiden Sep 25 '14 at 17:45
  • Yeah. You need an instance of `Context` to call that method on. It's a method of `Context`. – FD_ Sep 25 '14 at 17:47
  • So how do I do this exactly? – igorfeiden Sep 25 '14 at 17:54
  • You have to pass a reference to an instance of Context to the place where you are executing this code. Where do you run this code? What is the super class of the class? – FD_ Sep 25 '14 at 17:56
  • `public class BarCodeFragment extends Fragment implements OnItemClickListener` The call is in `OnCreateView` after I set content to the textview. – igorfeiden Sep 25 '14 at 17:57