Search code examples
androidoptionmenu

How To Creating Dynamic Menu to show on Fragment


I have a class BaseFragment i was create a private menu and set that menu from

@Override 
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.main, menu);
    this.menu = menu;
}

in main.xml i have :

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- Search / will display always -->
<item android:id="@+id/action_search"
      android:icon="@drawable/ic_action_search"
      android:title="@string/action_search"
      android:showAsAction="ifRoom"/>

<!-- Refresh -->
<item android:id="@+id/action_refresh"
      android:icon="@drawable/ic_action_refresh"
      android:title="@string/action_refresh"
      android:showAsAction="ifRoom" />

<!-- Download -->
<item android:id="@+id/action_download"
      android:icon="@drawable/ic_action_download"
      android:title="@string/action_download"
      android:showAsAction="never"/>

<!-- Favorite -->
<item android:id="@+id/action_favorites"
      android:icon="@drawable/ic_action_favorites"
      android:title="@string/action_favorites"
      android:showAsAction="never" />
</menu>

and i have another fragments FragmentA and FragmentB extends to that BaseFragment. In FragmentA i want to show All menu and all is OK when running the app, but in FragmentB i want to show the download and and favorite whitout search and refresh.

I was try to create a method on base to manipulate the visibility on menuitem and my menu always return null.

protected void setSearchable(boolean isSearchable){
    menu.findItem(R.id.action_search).setVisible(isSearchable);
}
protected void setHasRefreshFuction(boolean isHasRefreshFunction){
    menu.findItem(R.id.action_refresh).setVisible(isHasRefreshFunction);
}
protected void setDownloadable(boolean isDownloadable){
    menu.findItem(R.id.action_download).setVisible(isDownloadable);
}
protected void setFavorite(boolean isFavorite){
    menu.findItem(R.id.action_favorites).setVisible(isFavorite);
}

i call that method on onCreate() in FragmentB like this:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setDownloadable(true);
    setFavorite(true);
    setHasRefreshFuction(false);
    setSearchable(false);
}

Can someone help me please.... i was read many tutorial and doesn't find an answer to make this. note : I was setHasOptionsMenu(true); in oncreate in BaseFragment


Solution

  • The easiest way would be to override onCreateOptionsMenu in FragmentB again.

    @Override 
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.main, menu);
        menu.findItem(R.id.action_search).setVisible(false);
        menu.findItem(R.id.action_refresh).setVisible(false);
        this.menu = menu;
    }