简体   繁体   English

从Android菜单项图标中获取绘图

[英]get drawable from Android Menu Item Icon

I have a bookmark icon in a menu item. 我在菜单项中有一个书签图标。 I want to change the drawable in the icon depending on whether the bookmark has been pressed before or not. 我想更改图标中的drawable,具体取决于之前是否按过书签。

I have two drawbles, staro (meaning star orange) or starw(meaning star white). 我有两个标签,staro(意思是星橙)或starw(意思是星白)。 I just want to toggle this on press. 我只想在媒体上切换这个。

How can I know which drawble is in the icon in public boolean onOptionsItemSelected(MenuItem item) method. 如何知道public boolean onOptionsItemSelected(MenuItem item)方法中的哪个drawble在图标中。 Is it possible to know the drawable via the item. 是否可以通过该项目了解drawable。 what I know is that item.getIcon() is not the drawble. 我所知道的是item.getIcon()不是drawble。 I cannot compare item.getIcon() with R.drawable.starto 我无法将item.getIcon()R.drawable.starto进行比较

You could try 你可以试试

if (item.getIcon().getConstantState().equals(
        getResources().getDrawable(R.drawable.starto).getConstantState()
)) {
    ...
}

As mentioned here 如前所述这里

You can do the changes in onPrepareOptionsMenu() which is called every time before the menu is shown. 您可以在onPrepareOptionsMenu()中进行更改,每次在显示菜单之前调用该更改。 Its suitable to show/hide options based on some dynamic data. 它适合基于某些动态数据显示/隐藏选项。

If you already now the condition, you can directly call 如果你现在已经有条件,你可以直接打电话

if (condition_for_orange) {
  menu.findItem(resourceId).setIcon(R.drawable.staro);
} else {
  menu.findItem(resourceId).setIcon(R.drawable.startw);
}

You can use Shared Preference or some other global variable which can store the state which may help you to decide which icon to show now. 您可以使用共享首选项或其他可以存储状态的全局变量,这可以帮助您确定要显示的图标。

you can compare these too. 你也可以比较这些。

you can find id of drawable by 你可以找到可绘制的id

int identifier = getResources().getIdentifier("pic1", "drawable","android.demo");

and then you can compare this with R.drawable.starto `. 然后你可以将它与R.drawable.starto进行比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM