Android 工具栏中的购物车计数标记

Android 工具栏中的购物车计数标记,android,android-layout,Android,Android Layout,我的工具栏中有一个购物车计数。 我有一个主要活动和一些片段 增加购物车计数的代码如下所示 public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.home, menu); MenuItem getItem = menu.f

我的工具栏中有一个购物车计数。 我有一个主要活动和一些片段

增加购物车计数的代码如下所示

public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.home, menu);

    MenuItem getItem = menu.findItem(R.id.action_addcart);
    if (getItem != null) {
        cartCounterActionView = (CartCounterActionView) getItem.getActionView();
        cartCounterActionView.setCount(new Database(this).getCountCart(Common.currentUser.getPhone()));
        //Set a ClickListener, the text,
        //the background color or something like that
        cartCounterActionView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
                tx.replace(R.id.frame, new Cart());
                tx.commit();
            }
        });
    }

    return true;
}

此代码在我的主要活动中运行良好,但我想做的是,在我的片段中调用此购物车计数,以便我也可以在片段中设置计数。我想在oncreateoption旁边的另一个方法中调用它。有任何帮助吗?

请创建一个
菜单
成员变量,并在
OnCreateOptions菜单
中分配它:

private Menu myMenu;
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.home, menu);
    myMenu = menu;
    // now you can use myMenu to fetch your MenuItem outside onCreateOptionsMenu
    ...
}
或者,如果您只想从片段中运行
onCreateOptions菜单中的代码,则可以调用
getActivity().invalidateOptions菜单()