MenuItem.OnMenuItemClickListener 第二次点击时不工作

MenuItem.OnMenuItemClickListener not working when second click

我创建了片段并根据菜单项的 onclick 事件安排了它的可见性。当我第一次点击时,它工作正常但再次点击片段可见性不隐藏。图片说明;当我单击设置灰色片段显示时,再次单击时我想隐藏灰色片段但它没有做这些事情。

这是我的代码;

   @Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
     MenuItem item = menu.findItem(R.id.action_settings);
    item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            if (findViewById(R.id.frameLayout) != null)
            {
                FragmentTest fragmenttest = new FragmentTest();
                FragmentManager fm = getSupportFragmentManager();
                FragmentTransaction ft = fm.beginTransaction();
                if (fragmenttest.isVisible()) {
                    ft.hide(fragmenttest);

                } else {


                    if (fragmenttest.isAdded()) {

                    } else {
                        ft.add(R.id.frameLayout, fragmenttest, "Hello Fragment");
                    }

                    ft.show(fragmenttest);

                }
                ft.commit();

            }
            return false;
        }
    });
    return true;


}

移动

FragmentTest fragmenttest = new FragmentTest();

到 activity 的顶部。