所以,使用下面的代码,我得到listview项的值,我点击并将其复制到剪贴板,以便用户可以在以后粘贴它。
listView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) {
TextView textView = (TextView) view.findViewById(R.id.txt);
registerForContextMenu(textView);
}
}
);
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
//user has long pressed your TextView
menu.add(Menu.NONE, 0, Menu.NONE, "Copy");
//cast the received View to TextView so that you can get its text
TextView yourTextView = (TextView) v;
copiedMSG = yourTextView.getText().toString();
//System.out.println("Message Copied = : " + copiedMSG);
}
// This is executed when the user selects an option
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case 0:
ClipboardManager cm = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
cm.setText(copiedMSG);
Toast.makeText(getActivity(), "Copied", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onContextItemSelected(item);
}
}
这很好用,但问题是上下文菜单只出现在第二次我点击一个项目。第一次点击一个项目什么都没发生。
答案 0 :(得分:1)
这是因为在第一次点击之前没有为TextView
注册上下文菜单(这发生在您的OnItemClickListener
中)。
如果您希望最初为上下文菜单注册视图,则应该在列表适配器的getView()
功能中执行此操作。