Parsing an Android XML Resource Menu into a List of Objects

I can not solve this problem within 3 days. I have a simple XML resource for menus

<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/categoryEditButton" android:title="@string/edit" android:icon="@drawable/edit" /> <item android:id="@+id/categoryMoveUpButton" android:title="@string/move_up" android:icon="@drawable/up" /> <item android:id="@+id/categoryMoveDownButton" android:title="@string/move_down" android:icon="@drawable/down" /> <item android:id="@+id/categoryDeleteButton" android:title="@string/delete" android:icon="@drawable/trash" /> </menu> 

I want to get a List <MenuItem> after parsing this XML:

 public class MenuItem { private CharSequence text; private Drawable image; private int actionTag; //... getters and setters ... } 

I need this for non-standard manipulations with MenuItems and cannot work with this resource with standard methods, for example:

 ... MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.some_menu, menu); ... 

Can someone help me? Thanks.

+7
source share
3 answers

You can easily change the menu items at runtime .

Update after comment:

  • parse XML to get resource identifiers and resource types (images, lines, drawings, etc.)

  • Access to resources through the Resources class. Each type of resource has a different way of accessing it.

-one
source

This will help:

 ... PopupMenu p = new PopupMenu(this, null); Menu menu = p.getMenu(); getMenuInflater().inflate(R.menu.some_menu, menu); //Usage of menu System.out.println("LOG id: "+ menu.getItem(0).getItemId()); System.out.println("LOG title: "+ menu.getItem(0).getTitle()); System.out.println("LOG icon: "+ menu.getItem(0).getIcon()); ... 

Creating PopupMenu is just a trick for creating a Menu object that, when pumped, will be filled with the information defined on your xml.

+11
source

Thanks Raul. This does not work for 2.33. I found a solution here .

 private Menu newMenuInstance(Context context) { try { Class<?> menuBuilderClass = Class.forName("com.android.internal.view.menu.MenuBuilder"); Constructor<?> constructor = menuBuilderClass.getDeclaredConstructor(Context.class); return (Menu) constructor.newInstance(context); } catch (Exception e){ MyLog.GetMyLog().e(e); } return null; } 
+1
source

All Articles