SherlockFragment onCreateOptionsMenu is not calling

对着背影说爱祢 提交于 2019-12-06 08:07:33

The imports should be:

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

and not these of android OS!

Also try calling super method like:

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

    Log.i(TAG, "* onCreateOptionsMenu");
}

I had a same issue recently. And my code is very similar with yours that I use Fragment in PagerSlidingTabStrip...

My solution is something like this.

I don't do anything in my fragment but fix the source from PageSlidingTabStripFragment.java

PageSlidingTabStripFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
    adapter = new MainPagerAdapter(getChildFragmentManager());
    setHasOptionsMenu(true);
setRetainInstance(true);
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    Log.e("test", "Fragment onCreateOptionsMenu");
    int position = pager.getCurrentItem();

    if (position == 4) {
        inflater.inflate(R.menu.fragment_report_menu, menu);
    }

    super.onCreateOptionsMenu(menu, inflater);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.board_list_menu_new:
            ReportFragment fragment = (ReportFragment) adapter.getItem(pager.getCurrentItem());
            fragment.onMyOptionItemSelected();
            break;
    }
    return super.onOptionsItemSelected(item);
}

And that all.

This is not very clean solution and should be fixed in library. :)

Thanks, Wooram

This is the exact code I have written and it works fine.

import android.os.Bundle;
import android.util.Log;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;

public class First extends SherlockFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
    setHasOptionsMenu(true);

    super.onCreate(savedInstanceState);
    Log.i("TAG", "* created");

}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    menu.clear();
    menu.add("abcd").setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
    menu.add("efgh").setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);

    Log.i("TAG", "* onCreateOptionsMenu");
}

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!