Android does not solve the overflow menu bar displays the icon and set android: showAsAction = "ifRoom" but not in the navigation bar problem

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/weixin_43219615/article/details/100161793
  1. Set android: showAsAction = "ifRoom" property but not in the navigation bar display problem.
    Increase namespace xmlns:app="http://schemas.android.com/apk/res-auto", while using app:showAsAction="ifRoom".
  2. Set the icon property but does not display the icon problem.
    Use reflection to invoke a private method setOptionalIconsVisible, an icon will be displayed.
//setOptionalIconsVisible是私有的的,利用暴力反射可以调用
private void setOverflowIconVisible(int featureId, Menu menu) {
	//actionbar的featureId是8 ToolBar的是108
	if(featureId % 100 == Window.FEATURE_ACTION_BAR && menu != null) {
		if(menu.getClass().getSimpleName().equals("MenuBuilder")) {
			try {
				Method method = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
				method.setAccessible(true);
				method.invoke(menu, true);
			} catch(Exception e) {
			}
		}
	}
}

Guess you like

Origin blog.csdn.net/weixin_43219615/article/details/100161793