ActionBar中的按钮设置可见性?

时间:2015-02-11 11:45:24

标签: android android-fragments android-actionbaractivity

我有3个Fragments,而在Fragment3我希望在我的ActionBar中显示一个图标,这样可以正常工作但是当我回到其他片段如Fragment1和Fragment2时这个图标留下visible(true) 我尝试在片段item.setVisible(false)中添加onPause,但不起作用且图标保持在其他Fragments

我该如何解决?

XML

<item
    android:id="@+id/action_chat"
    android:icon="@drawable/batalha_icon_chat"
    android:title="Chat"
    app:showAsAction="ifRoom"
    android:visible="true"
    />

片段

public class Fragment3 extends Fragment implements View.OnClickListener {
    private Menu mMenu;

@Override
    public void onCreate(Bundle savedInstanceState) {    
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.battle_chat, menu);
    mMenu = menu;
    MenuItem mi = mMenu.findItem(R.id.action_chat);
    if(this.isVisible()){
        Log.i("VISIBLE->", "true");
        mi.setVisible(true);
    }else{
        Log.i("VISIBLE->", "false");
        mi.setVisible(false);
    }
    super.onCreateOptionsMenu(menu, inflater);
}


@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_chat:
                Fragment frag = new HelloBubblesActivity();
                FragmentTransaction ft = getFragmentManager().beginTransaction();
                ft.replace(R.id.fl, frag,"HelloBubblesActivity");     
                ft.commit();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }


 @Override
    public void onPause() {
        super.onPause();
    //API 9
    getActivity().supportInvalidateOptionsMenu();
}

1 个答案:

答案 0 :(得分:1)

您需要致电:invalidateOptionsMenu(); 这将调用onCreateOptionsMenu()