Search code examples
androidactionbarsherlockandroid-appcompatoncreateoptionsmenu

ABS to AppCompat


I am trying now to change ABS actionbar to AppCompat. I need to force the following code, whitch works fine with SherlockFragment, to work in android.support.v4.app.Fragment. I need to add custom view into Menu. How can I do this right in android.support.v4.app.Fragment?

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    menu.clear();
    View view = getLayoutInflater(getArguments()).inflate(R.layout.some_custom_layout, null);
    menu.add("ITEM").setActionView(view).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
}

Solution

  • Instead of

    void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
    

    and use

    void onPrepareOptionsMenu(Menu menu)
    

    then change

    menu.add("ITEM").setActionView(view).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
    

    to

    MenuItem menuItem = menu.add("SWITCHER");
    MenuItemCompat.setActionView(menuItem, view);
    MenuItemCompat.setShowAsAction(menuItem, MenuItemCompat.SHOW_AS_ACTION_ALWAYS);