Copy text from TextView on Android

前端 未结 6 1042
野趣味
野趣味 2020-12-02 21:10

I have a ListView where each item is a TextView.

I want to enable the long press behaviour similar to an EditText that display

6条回答
  •  不思量自难忘°
    2020-12-02 22:10

    I think I have a solution. Just call
    registerForContextMenu(yourTextView);

    and your TextView will be registered for receiving context menu events.

    Then override onCreateContextMenu in your Activity:

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        //user has long pressed your TextView
        menu.add(0, v.getId(), 0, "text that you want to show in the context menu - I use simply Copy");
    
        //cast the received View to TextView so that you can get its text
        TextView yourTextView = (TextView) v;
    
        //place your TextView's text in clipboard
        ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); 
        clipboard.setText(yourTextView.getText());
    }
    

    Hope this helps you and anyone else looking for a way to copy text from a TextView

提交回复
热议问题