无法获取在上下文菜单中单击的ListView位置

时间:2013-11-29 17:21:04

标签: java android contextmenu

我正在尝试创建一个上下文菜单,并对ListView中单击的行执行某些操作,但是当我尝试使用info.position

这是我的代码:

listView = (ListView) findViewById(R.id.listView1); // The list view
listView.setOnItemLongClickListener(new OnItemLongClickListener()
    {
        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,int pos, long id)  // One Long Click
        {
            registerForContextMenu(listView); // Registering the context menu
            Log.e(TAG, "Long Click!");
            return true;
        }
    });

@Override
public void onCreateContextMenu(ContextMenu menu, View v,
                                ContextMenu.ContextMenuInfo menuInfo) 
{      
    super.onCreateContextMenu(menu, v, menuInfo);
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.optmenu, menu);
}

@Override
public boolean onContextItemSelected(MenuItem item) 
{
    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();

    switch(item.getItemId())
    {
        case R.id.item3:
            RemoveTask(info.position);
        break;
    }

    return true;
}

onContextItemSelected(MenuItem item)中,每当我尝试使用行info.position(suppost返回listview的位置的int)时,程序就会崩溃......

(它没有进入RemoveTask,我已经完成了...即使我尝试使用Log打印info.position,它也会崩溃我的应用程序).​​.....

谢谢!

编辑: 我使用的代码与我在此处发布的代码相同,但突然之间,菜单甚至不再出现了......

2 个答案:

答案 0 :(得分:1)

尝试拨打

registerForContextMenu(listView); // Registering the context menu
来自

下的onCreate方法的

listView = (ListView) findViewById(R.id.listView1); // The list view

答案 1 :(得分:1)

如果要为上下文菜单注册视图,则无需为视图设置OnLongClickListener。在您的情况下,可以在您的活动的onCreate()方法中为菜单注册ListView:

@Override
public void onCreate (Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    ...
    ...
    listView = (ListView) findViewById(R.id.listView1);
    registerForContextMenu(listView);
}

删除OnLongClickListener的代码,其余代码应保持不变:

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
{
    super.onCreateContextMenu(menu, v, menuInfo);
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.optmenu, menu);
}

@Override
public boolean onContextItemSelected(MenuItem item)
{
    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    switch(item.getItemId())
    {
        case R.id.item3:
            RemoveTask(info.position);
            break;
    }

    return true;
}