Search code examples
androidandroid-fragmentsandroid-actionbarandroid-listfragment

onOptionsItemsSelected not being used in Fragment


I'm trying to add a button to my menu bar in my ListFragment class. When I click the button, nothing happens though. The onCreateOptionsMenu method is never being called in the class. I've tried everything to get it working but it still won't work. Has anyone got any solutions?

I've attached my code below:

public class FragmentZero extends ListFragment {
public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        // use your custom layout
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_layout_zero, container, false);

        oslist = new ArrayList<HashMap<String, String>>();
        new JSONParse().execute();
        return view;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // Inflate the menu items for use in the action bar
        inflater.inflate(R.menu.main_fragment_zero, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    public boolean onOptionsItemsSelected(MenuItem item) {
    // Take appropriate action for each action item click
        switch (item.getItemId()) {
            case R.id.action_refresh:
                // check for updates action
                RefreshButton();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

Solution

  • Add setHasOptionsMenu(true) to your onCreateView() method and remove it in OnCreate().