Search code examples
androidarraysandroid-optionsmenu

Using Array size to control Options Menu size


I have an array of objects that changes in size as objects are added and removed. There is an options menu on my activity that I would like to be able to choose which object you see the details of.

How do I pass the array details to the xml file that is controlling the menu, so I can run a for loop to add an item to the menu for each object in the array?

I would want to achieve this -

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    for(int i=0; i < bikes.size(); i==){
    <item
        android:id="@+id/bikes(i)"
        android:title=bikes(i).getName()></item>
    }

</menu>

But of course I'm in xml, not java. How can I do it?

Thanks!


Solution

  • I would try the following code :

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            super.onCreateOptionsMenu(menu);
            for(int i=0; i < bikes.size(); i++){
    
              String bikeModelMenu = bikes.get(i).model;
              menu.add(0, i, 0, bikeModelMenu).setShortcut('3', 'c');
    
            }
    
    
            return true;
        }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {           
    
        switch (item.getItemId()) {
        case 0:
            // code for first select
            return true;
    
    
        }
        return super.onOptionsItemSelected(item);
    }