Search code examples
androidtextviewandroid-4.0-ice-cream-sandwich

how to make TextView selectable under api 11


I need to have a text that will be shown to the user, and it will be possible to select a part of it and copy it to the clipboard. But without the keyboard open. I know that on api 11 and newer i can just use

text.setTextIsSelectable (true);

But what is the solution to lower OS versions?


Solution

  • Use ContextMenu and CLIPBOARD_SERVICE:

    private TextView mTextView;
    
    protected final void onCreate(Bundle savedInstanceState) {
    ...
    registerForContextMenu(mTextView);
    }
    
    @Override
    public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
            TextView textView = (TextView) view;
            menu.setHeaderTitle(textView.getText()).add(0, 0, 0, R.string.menu_copy_to_clipboard);
    }
    
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        ((ClipboardManager) getSystemService(CLIPBOARD_SERVICE)).setText(mTextView.getText());
        return true;
    }