Fragments seem to be very nice for separation of UI logic into some modules. But along with ViewPager
its lifecycle is still misty to me. So Guru thoughts are b
I found another relatively easy solution for your question.
As you can see from the FragmentPagerAdapter source code, the fragments managed by FragmentPagerAdapter
store in the FragmentManager
under the tag generated using:
String tag="android:switcher:" + viewId + ":" + index;
The viewId
is the container.getId()
, the container
is your ViewPager
instance. The index
is the position of the fragment. Hence you can save the object id to the outState
:
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("viewpagerid" , mViewPager.getId() );
}
@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
if (savedInstanceState != null)
viewpagerid=savedInstanceState.getInt("viewpagerid", -1 );
MyFragmentPagerAdapter titleAdapter = new MyFragmentPagerAdapter (getSupportFragmentManager() , this);
mViewPager = (ViewPager) findViewById(R.id.pager);
if (viewpagerid != -1 ){
mViewPager.setId(viewpagerid);
}else{
viewpagerid=mViewPager.getId();
}
mViewPager.setAdapter(titleAdapter);
If you want to communicate with this fragment, you can get if from FragmentManager
, such as:
getSupportFragmentManager().findFragmentByTag("android:switcher:" + viewpagerid + ":0")