android通过contextmenu获取listview项目

时间:2015-02-19 06:13:16

标签: android listview

在我的应用程序中,我在Listview上注册了ContextMenu,我希望按上下文菜单点击Listview项。例如,如果我在列表视图中有两行具有此结构:

public class StructReceiveSms{

    public int     userID;
    public String  username;
}

我的适配器可以在listview中显示用户名。现在我在下面的代码可以在列表视图上定义conext菜单:

public class FragmentSmsReceiveMaster extends Fragment {

    private static final Boolean        DEBUG    = true;
    public ArrayAdapter                 adapter;
    private ArrayList<StructReceiveSms> receiveSmsArray;
        .
        .
        .
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        .
        .
        .
        smsView = (ListView) view.findViewById(R.id.listView);
        smsView.setAdapter(adapter);
        registerForContextMenu(smsView);
        .
        .
        .
}
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
        String[] menuItems = getResources().getStringArray(R.array.SmsMasterContextMenu);
        for (int i = 0; i < menuItems.length; i++) {
            menu.add(Menu.NONE, i, i, menuItems[i]);
        }
    }


    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        int menuItemIndex = item.getItemId();
        String listItemName = adapter.getItem(info.position) + "";

        /* GET CLICKED LISTVIEW ITEM AFTER CHOOSE CONTEXTMENU MENU ITEMS */

        Toast.makeText(G.currentActivity, listItemName, Toast.LENGTH_SHORT).show();
        return true;
    }
}

现在点击上下文菜单项后,我可以通过menuItemIndex获取用户点击的内容,但我无法获取Listview功能中的onContextItemSelected个项目。例如,在第一个项目上打开上下文菜单我可以获得userIDusername并显示它。怎么做,谢谢

1 个答案:

答案 0 :(得分:1)

由于您的适配器数据列表包含StructReceiveSms个对象,adapter.getItem(info.position)中的onContextItemSelected()调用将返回上下文菜单打开的列表项,但需要将其转换为StructReceiveSms类型。由此,您可以获得所需的userIDusername

public boolean onContextItemSelected(MenuItem item)
{
    ...
    StructReceiveSms listItem = (StructReceiveSms) adapter.getItem(info.position);
    String selectedName = listItem.username;
    int selectedId = listItem.userID;
    ... 
}

这假设您没有覆盖适配器的getItem()方法以返回其他内容,但我想如果您有,则会显示出来。