我想将一些数据存储到弹出菜单中的每个项目中。所有项目都根据提要返回的结果在 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();
}
}
最佳答案
您可以使用 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();
}
}
关于java - 获取所选项目在Android弹出菜单类中的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36359536/