在Android弹出菜单类中获取所选项目的位置

时间:2016-04-01 14:56:31

标签: java android

我想将一些数据存储到弹出菜单中的每个项目中。基于从馈送返回的结果,以for循环以编程方式对所有项目进行充气。

在下面的示例中,我使用HashMap storedOption来存储每个项目的数据,并将循环索引作为键。但我需要找到一种方法来获取onMenuItemClick中所选项目的位置,以便我可以从storedOption检索数据。谁能告诉我怎么做?除了以下尝试之外,我还尝试了item.getOrder(),但无论菜单中有多少项,它总是返回0。

 public DynamicPopUpMenu{

    private Map<String,FeatureList> storedOption = new HashMap();

    public void main(final Context context,List<FeatureList> featureList){

        int count = 0;
        PopupMenu menu = new PopupMenu(context, featureList);
        for(FeatureList f:featureList) {
            MenuItem item = menu.getMenu().add(f.key);
            storedOption.put(count, f);
            count++;
        }

        menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            public boolean onMenuItemClick(MenuItem item) {
               AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
                int position = info.position;
                new ShowToast(context,Integer.toString(position)); // show position in a toast
                return true;
            }
        });

        menu.show();
    }

  }

1 个答案:

答案 0 :(得分:1)

您可以使用featureList.key作为storeOption的密钥,并使用item.getItemId();storeOption获取值。

像这样:

 public DynamicPopUpMenu{

    private Map<String,FeatureList> storedOption = new HashMap();

    public static void main(final Context context,List<FeatureList> featureList){

        int count = 0;
        PopupMenu menu = new PopupMenu(context, featureList);
        for(FeatureList f:featureList) {
            MenuItem item = menu.getMenu().add(f.key);
            storedOption.put(f.key, f);
            count++;
        }

        menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            public boolean onMenuItemClick(MenuItem item) {
               AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
                int id = item.getItemId();
                FeatureList mFeatureList = (FeatureList)storedOption(id)
                new ShowToast(context,Integer.toString(value)); // show position in a toast
                return true;
            }
        });

        menu.show();
    }

  }