My problem is to initially load the fragment directly and also I want to call a method fragment is visible to the user.
For loading the correct fragment, I use viewPager.setCurrentItem() in onCreate. It works well.
FragmentActivity code:
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
mTabsAdapter = new TabsPlayerAdapter(this, mRadioList);
mMainViewPager.setAdapter(mTabsAdapter);
mMainViewPager.setOnPageChangeListener(this);
mMainViewPager.setCurrentItem(2);
}
To a method called fragment Current, I use the onPageSelected viewPager. It works well.
FragmentActivity code:
@Override
public void onPageSelected(int position) {
Log.d(TAG, "onPageSelected - position: " + position);
((PlayerFragment) mTabsAdapter.mSparseFragment.get(position))
.startAnnimation();
}
FragmentStatePagerAdapter code:
@Override
public Fragment getItem(final int position) {
Log.d(TAG, "getItem - position: " + position);
Bundle args = new Bundle();
args.putString("num", mRadioModel.get(position).name);
mSparseFragment.put(position, Fragment.instantiate
(mContext,PlayerFragment.class.getName(), args));
return mSparseFragment.get(position);
}
FragmentStatePagerAdapter code :
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
Log.d(TAG, "destroyItem - position: " + position);
mSparseFragment.remove(position);
}
I can do these two things separately. But when I try to use the two together, I have a "NullPointerException" when I call my fragment.
I saw that onPageSelected is called before the getItem in my Adapter.
You’ll know that items are available when onAttachedToWindow is called. At the moment you call setCurrentItem, the adapter has not been used to create views yet. (setAdapter is not sufficient to know that all have been inflated)
Else, you can consider setting your listener after setting the currentItem, therefore not having a animation when opening the fragment.