The recent project started with the toolbar control, where there is a need to dynamically change the MenuItem in toolbar. Such as:
1, the first thought of the method is the use of toolbar self-addview () and Removeview ().
After testing, dynamic add and delete view No click effect, you need to add, and if you need to overflow effect, you need to implement PopupMenu, so this method is suitable for less view situation.
2, toolbar is used to replace the Actionbar, used Actionbar should be familiar with Actionmenuview, using Actionmenuview with toolbar can be realized dynamically change toolbar MenuItem, What actually changed is the item in the Actionmenuview.
1), in the layout file of the Actionmenuview as toolbar child;
<Android.support.v7.widget.Toolbarxmlns:android= "Http://schemas.android.com/apk/res/android"style= "@style/toolbar"> <Android.support.v7.widget.ActionMenuViewAndroid:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:id= "@+id/action_menu_view"android:layout_gravity= "Right"/></Android.support.v7.widget.Toolbar>
Among them Style/toolbar are as follows:
<stylename= "ToolBar"> <Itemname= "Android:layout_width">Match_parent</Item> <Itemname= "Android:layout_height">Wrap_content</Item> <Itemname= "Android:id">@id/toolbar</Item> <Itemname= "Android:background">@color/myprimarycolor</Item> <Itemname= "Theme">@style/toolbartheme</Item> <!--seemingly invalid - <Itemname= "Popuptheme">@style/toolbarpopuptheme</Item> </style> <stylename= "Toolbartheme"Parent= "ThemeOverlay.AppCompat.Light"> <Itemname= "Android:textcolorprimary">@color/abc_primary_text_material_dark</Item> <Itemname= "Android:textcolorsecondary">@color/abc_primary_text_material_dark</Item> <Itemname= "Android:colorbackground">@color/myprimarycolor</Item> </style> <stylename= "Toolbarpopuptheme"Parent= "ThemeOverlay.AppCompat.Light"> <Itemname= "Android:textcolorprimary">@color/abc_primary_text_material_light</Item> <Itemname= "Android:textcolorsecondary">@color/abc_primary_text_material_light</Item> <Itemname= "Android:colorbackground">@color/myprimarycolor</Item> </style>
2), in the code, first in the activity of the OnCreate () Findview, and then add MenuItem where needed, and the use of the same method as the menu;
Actionmenuview = (Actionmenuview) Findviewbyid (R.id.action_menu_view); // set MenuItem Click event actionmenuview.setonmenuitemclicklistener (this); // clear the previous MenuItem Actionmenuview.getmenu (). Clear (); // Add a new MenuItemGetmenuinflater (). Inflate (R.menu.xxx,actionmenuview.getmenu ());
As follows:
3), click the event corresponding: Implement Actionmenuview.onmenuitemclicklistener interface can.
Dynamically changing MenuItem in toolbar