我正在动态创建一个弹出菜单,其中的项目将从Web服务中填充。
情况是,解析已经在MainActivity.java
,但弹出菜单在BaseAdapter.java
类内。我在MainActivity.java
内的数组中添加了所有菜单项。请参考下面的代码:
try {
JSONArray jsonArray = new JSONArray(menuItemsResponse.toString());
for (int i = 0; i < jsonArray.length(); i++){
JSONObject object = jsonArray.getJSONObject(i);
String strMenuItemNames = object.getString("Name");
listMenuItems.add(strMenuItemNames);
}
} catch (Exception e) {
e.printStackTrace();
}
我正在使用List<String> listMenuItems
在listMenuItems.add(strMenuItemNames)
内添加项目。
现在,我想从BaseAdapter类中访问此listMenuitems
。下面是我在BaseAdapter类中的getView()
方法中的弹出菜单代码:
PopupMenu popupMenu = new PopupMenu(activity, imgDropDown);
popupMenu.getMenu().add() // array to be added here
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener({
// on click events for each item
});
任何有解决方案的人都请回复。
提前致谢!
答案 0 :(得分:0)
1.添加您需要在构造方法中使用的列表信息。
List<String> listMenuItems;
public MyAdapter(List<String> listMenuItems, Context context) {
...
}
2.在您的代码中使用它。
popupMenu.getMenu().add(listMenuItems.get(position));
试试这个。
public class MyAdapter extends BaseAdapter {
List<String> listMenuItems;
private LayoutInflater inflater;
private Context context;
public MyAdapter(List<String> listMenuItems, Context context) {
this.context = context;
this.listMenuItems = listMenuItems;
this.inflater = LayoutInflater.from(context);
}
...
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = inflater.inflate(R.layout.your_layout, null);
...
PopupMenu popupMenu = new PopupMenu(activity, imgDropDown);
// edited here
popupMenu.getMenu().add(listMenuItems.get(position)); // array to be added here
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener({
// on click events for each item
});
return view;
}
}
答案 1 :(得分:0)
您可以定义如下界面
interface MenuItemProvider {
getMenuItems(); // add parameters, returntype based on your need.
}
Activity实现此接口并通过返回在activity中准备的listItem来实现getMenuItems()方法。
现在,您的适配器应该有一个setter方法来设置此接口,如下所示。
class yourActivity extends <> implements MenuItemProvider {
// other implementation.
// pass this implementation to your base adapter.
baseadapterinstance.setMenuItemProvider(this);
getMenuItems(){
// return list items.
}
}
/*** BaseAdpater class. ***/
private MenuItemProvider menuItemProviderImpl;
void setMenuItemProvider(MenuItemProvider menuItemProviderImpl){
this. menuItemProviderImpl = menuItemProviderImpl;
}
// when you need to get the list, call
menuItemProviderImpl.getMenuItems();
希望这会有所帮助!!