How to add submenu items to ActionBar action in code? How to add submenu items to ActionBar action in code? android android

How to add submenu items to ActionBar action in code?


Yes, there is.

The addSubMenu method returns a SubMenu object. A SubMenu is also a Menu, so you can call add on it to add items to the submenu rather than the parent menu. Your code above is creating two different submenus for Form 1 and Form 2 rather than two items within a single New Form submenu.

Example:

SubMenu submenu = menu.addSubMenu(0, Menu.NONE, 1, "New Form").setIcon(R.drawable.ic_new_form);submenu.add("Form 1").setIcon(R.drawable.attachment);


Adding an ActionProvider maybe it's easier. You can try as explained here


You should consider to use an ActionProvider

example: https://gist.github.com/sibelius/7ca0b757492ff6740dec

Menu with action provider item

<menu xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools">    <item android:id="@+id/action_companies"        android:icon="@drawable/ic_list"        android:title="@string/action_companies"        app:actionProviderClass="com.example.MyActionProvider"        app:showAsAction="always"/></menu>

Code

public class MyActionProvider extends ActionProvider {    private Context mContext;    public MyActionProvider(Context context) {        super(context);        mContext = context;    }    @Override    public View onCreateActionView() {        //LayoutInflater layoutInflater = LayoutInflater.from(mContext);        return null;    }    @Override    public void onPrepareSubMenu(SubMenu subMenu) {        super.onPrepareSubMenu(subMenu);        subMenu.clear();        subMenu.add("menu 1");        subMenu.add("menu 2");        subMenu.add("menu 3");    }    @Override    public boolean hasSubMenu() {        return true;    }    @Override    public boolean onPerformDefaultAction() {        return super.onPerformDefaultAction();    }}