0

I have a ListView in my activity.On clicking on the list item it invokes another activity.In that activity I have implemented ViewPager and fragments.

When it loads first time onResume() ,onCreate() and onCreateView() method called twice, if I clicks on first list item. (i.e. it loads first and second fragment view) when I click on the any other List fragment except first then it calls onResume() ,onCreate() and onCreateView() methods three times (i.e. It loads previous and after and click view )

It is absoutely fine but I have google analytics code with which I have to track only current page so where I can put this code to load for only current page

My question is my googleAnalytics code tracs three or two pages at first time even user doesnot gone through those pages how to avoid this ?

My code is as below for fragment 


    public class MainListActivity extends Activity{
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.v(TAG, "onCreate()");
    CustomFragmentPagerAdapter adapter = new CustomFragmentPagerAdapter();
    viewPager.setAdapter(adapter);


    }
    }

//code for fragment adapter 

    public class CustomFragmentPagerAdapter extends FragmentPagerAdapter {
    public CustomFragmentPagerAdapter(FragmentManager fm) {
            super(fm);

        }
    @Override
        public Fragment getItem(int pos) {
            CustomFragment customFragment = new CustomFragment();
            arrayList.add(customFragment);
            return customFragment;


    }




    @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return arrayList.size();
        }

    }


//code for fragment

public class CustomFragment extends Fragment{
public CustomFragment() {
        super();

    }
@Override
    public void onResume() {
        super.onResume();
        Log.v(TAG, "onCreate -Resume");
    }
    @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            Log.v(TAG, "onCreate");
    }
@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        Log.v(TAG, "onCreateView");
return myAnyView;

}
}
Anand Phadke
  • 531
  • 3
  • 28

1 Answers1

0

The problem is that the onResume() method is called for all your fragments, that is including the invisible ones. Check gorn's answer here: How to determine when Fragment becomes visible in ViewPager

You have to override

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);

    if (isVisibleToUser) {
        // Your logic
    }

and do your logic in there.

Community
  • 1
  • 1
bogdan
  • 338
  • 6
  • 10