How to add a menu to a fragment?

When I use a snippet, I do not get the menu in the ActionBar. I don't know where the problem is with the code, despite the implementation of the onCreateOptionsMenu () method. Here is the code I'm using:

public class LesAvis extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    setHasOptionsMenu(true);
    View rootView = inflater.inflate(R.layout.avis, container,false);
    ListView listeAvis = (ListView) rootView.findViewById(R.id.listView);
    return rootView;

}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.my_menu, menu);
    super.onCreateOptionsMenu(menu,inflater);
}

}

However, when I use this piece of code to implement the onCreateOptionsMenu () method, I get what I want (the menu in my action bar):

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    menu.add("Compte")
    .setIcon(R.drawable.ic_compte)
    .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
    menu.add("Compte")
    .setIcon(R.drawable.ic_historique)
    .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
    menu.add("Compte")
    .setIcon(R.drawable.ic_param)
    .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
}
+4
source share
3 answers

To add a menu for each fragment, you have to go through many steps:

1) First, add setHasOptionsMenu (true) to the onCreateView () snippet, as shown below:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
....
}

2) Override the onCreateOptionsMenu () fragment as shown below:

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) 
{
inflater.inflate(R.menu.menu_above_details_fragment, menu);
return;
}

3) onOptionsItemSelected() :

@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
    return true;
}
Intent i;
switch (item.getItemId()) {
case R.id.action_param:
    i = new Intent(this, Settings.class);
    startActivity(i);
    return true;

case R.id.action_history:
    i = new Intent(this, HistoryMenu.class);
    startActivity(i);
    return true;
}
return onOptionsItemSelected(item);
}

4) onOptionsItemSelected(), onCreateOptionsMenu().

+11

, : setHasOptionsMenu(true);

0

Call setHasOptionsMenu(true)in onCreate()instead onCreateView().

0
source

All Articles