我正在尝试在ViewPager中扩充Fragments。当它第一次膨胀时,它会调用onCreateOptionMenu()但不会使工具栏膨胀。
一旦ViewPager达到setoffscreenpagelimit片段数,它就会开始显示片段中的工具栏。
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onViewCreated(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
((AppCompatActivity) getActivity()).getSupportActionBar().setHomeButtonEnabled(true);
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
Activity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
mViewPager = (ViewPager) findViewById(R.id.viewPager);
mViewPager.setOffscreenPageLimit(4);
mPagerAdapter = new PagerAdapter(getFragmentManager());
mViewPager.setAdapter(mPagerAdapter);
}
PagerAdapter.java:
public class PagerAdapter extends FragmentStatePagerAdapter {
Cursor mCursor;
public PagerAdapter(FragmentManager fm) {
super(fm);
//cursor initialization
}
@Override
public Fragment getItem(int position) {
Fragment fragment = MyFragment.newInstance(position);
return fragment;
}
@Override
public int getCount() {
if (mCursor == null)
return 0;
else
return mCursor.getCount();
}
public void swapCursor(Cursor cursor){
mCursor = cursor;
notifyDataSetChanged();
}
}
尝试从https://code.google.com/p/android/issues/detail?id=29472& OptionsMenu of Fragments in Viewpager showing each other's Buttons
仍然无法弄清楚为什么前4个片段没有膨胀。任何人都可以帮忙吗?
谢谢!