动态更改选项菜单背景

问题描述:

我在菜单选项中有一个“购物车”项目,我想显示购物车中的产品数量,如下所示。动态更改选项菜单背景

enter image description here

要做到这一点我想创建几个图像与数字1到9 9+并打开菜单时设置正确的图像作为对应的菜单选项项目的背景。

我该怎么做,即如何动态地更改菜单选项的背景?

感谢

覆盖onPrepareOptionsMenu()菜单的方法来进行。它被称为每次用户点击Menu按钮。

@Override 
public boolean onPrepareOptionsMenu(Menu menu) { 
    // Let's find id of resource for drawable with required count 
    // assuming you have cartIcon1.png, cartIcon2.png etc 
    // in your `drawable` folder 
    int resId = getResources().getIdentifier("cartIcon" + numberOfElementsInCart, "drawable", getPackageName()); 

    if (resId != 0) 
     menu.findItem(R.id.cart).setIcon(resId); 
    // If resource was not found, set default icon 
    else 
     menu.findItem(R.id.cart).setIcon(R.drawable.defaultCart); 

    return true; 
} 

重载背景是非常困难的,我相信这是更方便易到有车和数字图标,因为你已经png格式每个号码

下面是一个可怕的,可怕的黑客攻击,改变菜单的背景图片 - 请注意,它会改变所有的菜单项的背景。现在可能有一种更简单的方法来做到这一点,但这是我在大约一年前发现的唯一方法。

设置菜单项的图标是一个容易得多,并且可以在onPrepareOptionsMenu

// Hack to make the menu item selector blue 
    protected void setMenuBackground(final int id) 
    { 
     if(getLayoutInflater().getFactory() != null) 
      return; 
     getLayoutInflater().setFactory(new Factory() 
     { 
      @Override 
      public View onCreateView(String name, Context context, AttributeSet attrs) 
      { 
       if(name.equalsIgnoreCase("com.android.internal.view.menu.IconMenuItemView")) 
       { 
        try 
        { 
         LayoutInflater li = getLayoutInflater(); 
         final View view = li.createView(name, null, attrs); 
         //What? 
         //Well the Android system is going to set the background after this is method is done 
         //so we run it later to override the override. Simples? 
         new Handler().post(new Runnable() 
         { 
          public void run() 
          { 
           view.setBackgroundResource(id); 
          } 
         }); 
         return view; 
        } 
        catch(InflateException e) 
        { 
        } 
        catch(ClassNotFoundException e) 
        { 

        } 
       } 
       return null; 
      } 
     }); 
    }