动态更改选项菜单背景

时间:2011-11-17 13:03:07

标签: android menu background

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

enter image description here

为了达到这个目的,我想创建一些数字从1到9和9+的图像,并在打开菜单时将正确的图像设置为相应菜单选项的背景。

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

由于

2 个答案:

答案 0 :(得分:0)

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

设置菜单项的图标要容易得多,可以在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;
            }
        });
    }

答案 1 :(得分:0)

覆盖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

相关问题