[英]Change the icon to Toolbar Android
How can I get an icon from the toolbar to be changed to a new one that I get with a method that is seen in a bbdd. 如何从工具栏中将图标更改为我使用bbdd中显示的方法获得的新图标。 The problem is that I can not access the event that updates the activity to be able to change the icon. 问题是我无法访问更新活动的事件以便能够更改图标。 I tried with the onPrepareOptionsMenu method, but I can not make it work. 我尝试使用onPrepareOptionsMenu方法,但我无法使其工作。 I have not been able to do this by putting the code in onStart because it tells me that the menu object is empty or invalid. 我无法通过将代码放在onStart中来执行此操作,因为它告诉我菜单对象为空或无效。
public boolean onPrepareOptionsMenu(Menu menu) {
menu.clear();
Drawable iconoMenu = obtenerIconoMenuCarro();
getMenuInflater().inflate(R.menu.menu_categorias, menu);
menu.getItem(0).setIcon(iconoMenu);
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_categorias, menu);
Drawable iconoMenu = obtenerIconoMenuCarro();
menu.getItem(0).setIcon(iconoMenu);
return true;
}
My activities are extended by AppCompactActivity and loaded through an AdapterView. 我的活动由AppCompactActivity扩展并通过AdapterView加载。 And I have the problem when I go back to the fragmentDialog or since the next activity. 当我回到fragmentDialog或下一个活动时,我遇到了问题。
Thanks. 谢谢。
For me the simplest way was to keep a reference to the MenuItem for later use. 对我来说,最简单的方法是保留对MenuItem的引用以供以后使用。
Obtain when the menu item is inflated. 菜单项膨胀时获取。
MenuItem menuItem;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_menu, menu);
//find the menu item from the id
menuItem = menu.findItem(R.id.myMenuItem);
return true;
}
Then change the image where you need to with mipmap resource or @drawable. 然后使用mipmap资源或@drawable更改所需的图像。
menuItem.setIcon(R.mipmap.ic_other_icon);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.