[英]Android open ContextMenu on short click + pass item clicked details
[英]ID of item clicked - Android ContextMenu
G'day,
我有一个用各种文本值填充的ListView,并且我想让它在长按并打开上下文菜单时可以将文本复制到长按的ListItem中。 到目前为止,我已经弹出带有“复制”选项的上下文菜单:
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
{
//this was following another question but I don't know what to do with it
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
long selectedId = info.id;
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context, menu);
}
public boolean onContextItemSelected(MenuItem item)
{
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId())
{
case R.id.copy:
//used to be in a function but wasn't sure about views
//yes I know it's depreciated but it works ;)
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
TextView clicked = (TextView)this.findViewById(???);
clipboard.setText(clicked.getText());
Context context = getApplicationContext();
Toast copied = Toast.makeText(context, "Story copied to clipboard.", Toast.LENGTH_LONG);
copied.show();
return true;
default:
return super.onContextItemSelected(item);
}
}
谢谢
我认为您已经回答了自己的问题。 ID为:
long selectedId = info.id;
设置一个变量来保存被单击的视图:
View clicked;
然后在其上创建上下文菜单时为其分配一个值:
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
{
clicked = v;
//this was following another question but I don't know what to do with it
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
long selectedId = info.id;
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context, menu);
}
现在,您可以在最终方法中使用它:
public boolean onContextItemSelected(MenuItem item)
{
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId())
{
case R.id.copy:
//used to be in a function but wasn't sure about views
//yes I know it's depreciated but it works ;)
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
clipboard.setText(clicked.getText());
// this should work now properly.
Context context = getApplicationContext();
Toast copied = Toast.makeText(context, "Story copied to clipboard.", Toast.LENGTH_LONG);
copied.show();
return true;
default:
return super.onContextItemSelected(item);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.