2

I am trying to copy an item text from a list view using onCreateContextMenu OnCreateContextMenu and ListView items and Copy text from TextView on Android but I don't know how to relate the click on the copy in the menu to the listView.

My current code, open up a menu with copy, and I have no idea how to get the text after copy was clicked

 @Override
 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
     super.onCreateContextMenu(menu, v, menuInfo);
        menu.add(0, v.getId(), 0, "copy");

}

@Override  
public boolean onContextItemSelected(MenuItem item) {  
    if(item.getTitle()=="copy"){}  
    else {return false;}  
return true;  
}  

thank you for your help

Community
  • 1
  • 1
Quantico
  • 2,398
  • 7
  • 35
  • 59

1 Answers1

5

Issue was solved , the following solution include support for both API 1-11 and above 11

@SuppressLint("NewApi")
@Override  
public boolean onContextItemSelected(MenuItem item) {  
    if(item.getTitle().equals(copy)){
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
        int index = info.position;
        String textTocopy =adapter.getItem(index-1).title;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); 
            ClipData clip = ClipData.newPlainText("simple text",textTocopy);
            clipboard.setPrimaryClip(clip);}
        else{
            android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            clipboard.setText(textTocopy);

        }
    }  
    else {return false;}  
    return true;  

}  
Quantico
  • 2,398
  • 7
  • 35
  • 59
  • 1
    `if(item.getTitle()=="copy"){...}` - This is incorrect. First, comparing the strings with `==` operator in java may result not as you expect. If you want to compare one string to any text you should use `.equals("any text")` (or `"any text".equals()` - in this way you should not check for `NULL`) and not `==`. Second, you should not compare to title at all (result will be different (in general) for different languages). Instead, you should compare to the item id: `item.getItemId() == R.id.` – Prizoff Mar 22 '13 at 16:27
  • Also, why you are comparing `Build.VERSION` with `_MR2` release? simple `HONEYCOMB` is enough: `(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)` – Prizoff Mar 22 '13 at 16:46