Android add icon in toolbar inside a fragment

时间:2015-06-15 14:25:23

标签: android android-actionbar-compat android-toolbar

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 个答案:

答案 0 :(得分:6)

在您的片段中,在onCreateView()方法中,您必须添加:

setHasOptionsMenu(true);

否则永远不会调用onCreateOptionsMenu()

答案 1 :(得分:0)

您可能需要使用invalidateOptionsMenu()来告诉片段重绘这样的菜单操作......

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