Define a menu resource and use it inside ActivityFragment

suggest change

Define a menu in res/menu

<?xml version="1.0" encoding="utf-8"?>
<menu
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/first_item_id"
        android:orderInCategory="100"
        android:title="@string/first_item_string"
        android:icon="@drawable/first_item_icon"
        app:showAsAction="ifRoom"/>

    <item
        android:id="@+id/second_item_id"
        android:orderInCategory="110"
        android:title="@string/second_item_string"
        android:icon="@drawable/second_item_icon"
        app:showAsAction="ifRoom"/>

</menu>

For more options of configuration refer to: Menu resource

Inside Activity:

An activity uses the one-argument onCreateOptionsMenu:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_resource_id, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    // Set visibility, text, or icons here.
    return super.onPrepareOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.first_item_id:
            return true;
    }
    return super.onOptionsItemSelected(item);
}

Inside a Fragment, call setHasOptionsMenu(true) and use the two-argument onCreateOptionsMenu(Menu, MenuInflater). Call getActivity().invalidateOptionsMenu() when the items need to be rebuilt.

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    setHasOptionsMenu(true);
    return inflater.inflate(R.layout.your_fragment, container, false);
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents