菜单项未显示在导航抽屉视图寻呼机片段中

时间:2014-08-28 13:53:35

标签: android android-fragments tabs

我有一个带有2个片段的导航抽屉,片段A和片段B.片段B是带有视图寻呼机的片段,有片段标签1和片段标签2.我试图在片段tab1和片段标签中显示搜索视图2。我尝试在片段选项卡1中调用setHasOptionsMenu(true)但是没有调用onCreateOptions(),因此从不显示searchview。任何人都可以帮助如何使这个工作?我遵循了本教程:View Pager+fragments+navdrawer

片段2(持有视图寻呼机)

public class TabsFragment extends SherlockFragment {

private PagerTitleStrip titleStrip;
private Menu menu;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.tabs_swipe, container, false);
    // Locate the ViewPager in viewpager_main.xml
    ViewPager mViewPager = (ViewPager) view.findViewById(R.id.pager);
    // Set the ViewPagerAdapter into ViewPager
    mViewPager.setAdapter(new TabsPagerAdapter(getChildFragmentManager(),
            getSherlockActivity()));
    titleStrip = (PagerTitleStrip) view.findViewById(R.id.titlestrip);
    titleStrip.setTextColor(Color.WHITE);
    titleStrip.setBackgroundColor(Color.parseColor("#E6000000"));
    mViewPager.setCurrentItem(2);

    return view;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    setHasOptionsMenu(true);
}

@Override
public void onDetach() {
    Log.d("tabs frag","on detach");
    super.onDetach();
    try {
        Field childFragmentManager = Fragment.class
                .getDeclaredField("mChildFragmentManager");
        childFragmentManager.setAccessible(true);
        childFragmentManager.set(this, null);
    } catch (NoSuchFieldException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}

片段标签1:

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    setHasOptionsMenu(true); 
}


@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
     Log.d(TAG, "on create options");  // never called
    menu.clear();
    inflater.inflate(R.menu.main, menu);

    searchItem = menu.findItem(R.id.action_search);
    searchItem.setVisible(true);
    mSearchView = (SearchView) searchItem.getActionView();
}

UDPATE

尝试以下代码。片段选项卡1中的Searchview出现,但现在tab1中的适配器在执行onQueryTextchanged

时显示为null
if(adapter.getItem(mViewPager.getCurrentItem()) instanceof FragTab1)
    {
        FragTab1 fragment = (FragTab1) adapter.getItem(mViewPager.getCurrentItem());

        fragment.onCreateOptionsMenu(menu, inflater);
    }

@Override
public boolean onQueryTextChange(String newText) {

    searchAdapter.getFilter().filter(newText); // shows searchadapter is null eventhough I have filled it in onCreate.
    searched = true;
    return true;
}

1 个答案:

答案 0 :(得分:0)

使用Action Bar Compat代替ActionBar Sherlock解决它。猜猜Sherlock图书馆有关儿童片段的一些问题,或者可能是我错过了什么。但是Action Bar Compat工作得非常好,没有改变任何东西。