[英]How can I set the visibility of an ActionBar item in different fragment
我正在尋找一種方法來設置我的MainActivity中膨脹的MenuItem
的可見性,具體取決於我所在的Fragment
。
有關信息:我正在使用actionBarSherlock
, zxing
和一些google services
。
該應用程序是使用導航抽屜(使用abs)構建的,我也以這樣的方式操作FragmentStack
每次當我按下觸摸時我切換到另一個片段我回到Main Fragment
。
我的菜單在這里:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/button_generator" android:title="GENERER" android:icon="@drawable/ic_drawer"></item>
</menu>
這是我給菜單充氣的地方:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.d(TAG, "================= onCreateOptionsMenu ================= fragSt: " + fragmentStatus);
this.getSherlock().getMenuInflater().inflate(R.menu.main, menu);
mGenQrFromContacts = menu.findItem(R.id.button_generator);
return true;
}
我已嘗試過這里的解決方案,但在我的情況下不起作用。
你應該在Fragment
嘗試這個:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// ...
// call the method setHasOptionsMenu, to have access to the menu from your fragment
setHasOptionsMenu(true);
//...
}
// the create options menu with a MenuInflater to have the menu from your fragment
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.findItem(R.id.button_generator).setVisible(true);
super.onCreateOptionsMenu(menu, inflater);
}
這個,在你的Activity
:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.my_layout, menu);
menu.findItem(R.id.button_generator).setVisible(false);
return true;
}
希望這可以幫助。
當你想要改變片段時,你需要設置一個標志,指出你想要膨脹的菜單,然后你要做的就是調用活動中的invalidateOptionsMenu()
來再次調用onCreateOptonsMenu
並使用你設置的旗幟給你一個不同的菜單
我發現了一個技巧,你可能想嘗試一下。
public void displayMenu(boolean show) {
setHasOptionsMenu(show);
getActivity().invalidateOptionsMenu();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.