简体   繁体   中英

Getting the selected item's position in Android popup menu class

I want to store some data into every item in a popup menu. All of the items are inflated programatically in a for loop based on results returned from a feed.

In the following example, I use a HashMap storedOption to store each item's data with the loop indices as keys. But I need to find a way to get the position of the selected item in onMenuItemClick so that I can retrieve the data from storedOption . Can anyone tell me how to do that? Besides the following attempt, I have also tried item.getOrder() but it always returns 0 regardless of how many items it has in the menu.

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

  }

You could use featureList.key as the key of your storeOption and them use item.getItemId(); to get the value from storeOption .

Like this:

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

  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM