I have 3 fragments part of a navigation drawer
, one of which contains a viewpager. When I first load the app, the viewpager loads all the fragments. However, when I switch to another fragment using the navi-drawer and I switch back, one of the viewpager fragments is not loading. I have tried the code here and here but I'm not able to come up with a solution.
In my pageradapter code, in the switch case for different fragments; I have put a log for the position, and position 1 does not seem to be coming after the initial load of the app.
My question is, why is it that position 1 never gets called? Can someone explain it to me?
Here's my Pageradapter code:
class PagerAdapter extends FragmentStatePagerAdapter {
static HeartRate_Fragment heartRate_fragment;
static Calorie_Fragment calorie_fragment;
static Steps_Fragment steps_fragment;
int num;
public PagerAdapter(Context context, FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
//add new fragment here for homepage viewpager
Log.d("position",position+"");
switch (position) {
case 0:
if(calorie_fragment == null)
calorie_fragment = new Calorie_Fragment();
Log.d("flip",0+"");
return calorie_fragment;
case 1:
if(heartRate_fragment == null)
heartRate_fragment = new HeartRate_Fragment();
Log.d("flip",1+"");
return heartRate_fragment;
case 2:
if(steps_fragment == null)
steps_fragment = new Steps_Fragment();
Log.d("flip",2+"");
return steps_fragment;
default:
return null;
}
}
@Override
public int getCount() {
return num;
}
public HeartRate_Fragment getHRFragment()
{
return heartRate_fragment;
}
public Calorie_Fragment getCalorie_fragment()
{
return calorie_fragment;
}
public Steps_Fragment getSteps_fragment()
{
return steps_fragment;
}
class PagerAdapter extends FragmentStatePagerAdapter {
static HeartRate_Fragment heartRate_fragment;
static Calorie_Fragment calorie_fragment;
static Steps_Fragment steps_fragment;
int num;
public PagerAdapter(Context context, FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
//add new fragment here for homepage viewpager
Log.d("position",position+"");
switch (position) {
case 0:
if(calorie_fragment == null){
calorie_fragment = new Calorie_Fragment();
return calorie_fragment;
}else {
return getCalorie_fragment(); }
case 1:
if(heartRate_fragment == null){
heartRate_fragment = new HeartRate_Fragment();
return heartRate_fragment;}
else{ return getHRFragment();}
case 2:
if(steps_fragment == null){
steps_fragment = new Steps_Fragment();
return steps_fragment;
}
else{ return getSteps_fragment();}
default:
return null;
}
}
@Override
public int getCount() {
return 3;
}
public HeartRate_Fragment getHRFragment()
{
return heartRate_fragment;
}
public Calorie_Fragment getCalorie_fragment()
{
return calorie_fragment;
}
public Steps_Fragment getSteps_fragment()
{
return steps_fragment;
}
try this make sure you are using getChildFragmentManager();