I have an application with ViewPager
and three tabs, each displaying a fragment that I try to preserve in memory so that new fragments are not instantiated fragments at every tab / screen change.
public class TabsPagerAdapter extends FragmentPagerAdapter {
private Fragmento0 mFragmento0 = null;
private Fragmento1 mFragmento1 = null;
private Fragmento2 mFragmento2 = null;
public TabsPagerAdapter(FragmentManager fm, ViewPager viewPager) {
super(fm);
}
@Override
public Fragment getItem(int indice) {
switch(indice){
case 0:
if (mFragmento0 == null) {
mFragmento0 = new Fragmento0();
}
return mFragmento0;
case 1:
if (mFragmento1 == null) {
mFragmento1 = new Fragmento1();
}
return mFragmento1;
case 2:
if (mFragmento2 == null) {
mFragmento2 = new Fragmento2();
}
return mFragmento2;
}
return null;
}
...
Fragmento0
has a SeekBar
with the default value 60
, defined in the layout of it, and above it a TextView
reporting the current value of SeekBar
:
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:gravity="center_horizontal"/>
<SeekBar
android:id="@+id/seekBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="120"
android:progress="60"/>
This is the relevant snippet of Fragmento0.onCreateView()
:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragmento_0, container, false);
mTextView = (TextView)rootView.findViewById(R.id.textView);
mSeekBar = (SeekBar) rootView.findViewById(R.id.seekBar);
mTextView.setText(mSeekBar.getProgress() + " minutos");
...
}
When changing tab, I realize that SeekBar
behaves strangely: when I change its value to be different from the default and mute from tab 0 to tab 1, when I go back to tab 0 the value holds, which is expected. However when changing from tab 0 to tab 2, when returning to tab 0 the position of SeekBar
does not change but TextView
returns the default value 60
.
Debugging the code I discovered that Fragmento0.onCreateView()
is not being called in the first case, which I believe to be expected but is being called in the second. Because? I do not do any transactions with the fragments , I do not move any to the back stack for example.
According to the life cycle of the fragments , is this certain? How do I correct this behavior? Would you use onSaveInstanceState()
? (tried and did not work). But why in one case the view is recreated and the other not? And why does not calling the onCreateView()
, when doing inflate
in the layout, restore the default value of SeekBar
?