单击项目的ID - Android ContextMenu

时间:2011-11-08 10:17:33

标签: android listview contextmenu

天儿真好,
 我有一个填充了各种文本值的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);
    }
}

由于

2 个答案:

答案 0 :(得分:0)

设置一个变量来保存被点击的视图:

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);
    }
}

答案 1 :(得分:0)

我想你已回答了自己的问题。 id是:

long selectedId = info.id;