Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a menu in a fragment?

When I use a fragment, I don't get the menu in the ActionBar. I don't know where is the problem with the code despite the implementation of the onCreateOptionsMenu() method. Here's the code that I am 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 part of code for implementing the onCreateOptionsMenu() method, I get what I want(the menu in my actionbar):

@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);
}
like image 554
HiddenDroid Avatar asked Apr 28 '15 15:04

HiddenDroid


1 Answers

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

1) First of all, add setHasOptionsMenu(true) in the fragment's onCreateView() like below:

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

2) Override fragment's onCreateOptionsMenu() method as below:

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

3) Override the activity's onOptionsItemSelected() method like this:

@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) Don't override the fragment's onOptionsItemSelected(), nor activity's onCreateOptionsMenu().

like image 64
HiddenDroid Avatar answered Sep 27 '22 23:09

HiddenDroid