Android add icon in toolbar inside a fragment

6.9k views Asked by At

I implement a toolbar and replace it with my actionbar according to my requirments. Now I want to add an icon in toolbar inside a fragment. I tried onCreateOptionMenu() and pass my menu xml to it. But it wont work. I also tried some other things and googling but nothing works so far. Does anybody have any idea about this. Here is my fragment code

public class Fragment_FavouriteLocations extends Fragment {
    public Fragment_FavouriteLocations() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        return inflater.inflate(R.layout.fragment_main_fav_location_row_item, container, false);


    }

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

    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.edit_button) {
            Toast.makeText(getActivity(), "", Toast.LENGTH_LONG).show();
            return true;
        }
//
//      if(id == R.id.action_search){
//          Toast.makeText(getApplicationContext(), "Search action is selected!", Toast.LENGTH_SHORT).show();
//          return true;
//      }

        return super.onOptionsItemSelected(item);
    }

}

Here is my menu xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:mayApp="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/edit_button"
        mayApp:icon="@android:drawable/ic_menu_edit"
        android:title="Edit"
        mayApp:showAsAction="always" />
</menu>

Thanks in advance

2

There are 2 answers

1
Gabriele Mariotti On BEST ANSWER

In your Fragment, in the onCreateView() method, you have to add:

setHasOptionsMenu(true);

Otherwise the onCreateOptionsMenu() is never called.

0
Abdullah al foqha On

you may need to use invalidateOptionsMenu() to tell the fragment to redraw the menu actions like this ...

        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            getActivity().invalidateOptionsMenu();
            setHasOptionsMenu(true);
        }