0

I am using a ViewPager plugged to a FragmentStatePagerAdapter. Each fragment contains a listview. In this listview I wish to display ads and make calls to a analytics server. I only want to make those calls when the user navigates to a fragment (so I cannot use the onCreateView or onActivityCreated events in the Fragment). Is there an event I can hook on to this end ?

Update I realized that the way I am fetching my current fragment is flawe

    @Override
    public void onPageSelected(int page) {
      this.currentPage = page;
      tabsAdapter.getItem(page);
    }

getItem(int position) in the pager is actually responsible for instanciating the fragments, so it would create a new unattached fragment (hence getActivity() returning null). I think I will us an approach where I keep a map of the fragments (<Position, Fragment>), i will remove the fragment from the map when destoryItem is called in the pagerAdapter.

blahdiblah
  • 33,069
  • 21
  • 98
  • 152
yann.debonnel
  • 766
  • 9
  • 22

2 Answers2

1

How about this:

http://developer.android.com/reference/android/support/v4/view/ViewPager.OnPageChangeListener.html

The onPageSelected(int) method sounds like it does what you want.

lyricsboy
  • 2,999
  • 24
  • 21
  • I tried this, but on this event if I try to launch my data tasks I need getActivity() for the context, getActivity() will return null – yann.debonnel Jul 31 '12 at 15:51
  • It would have been helpful if you had mentioned that requirement in the question :). Can you update with some sample code that illustrates the problem? I am somewhat surprised that onPageSelected would be called before onAttach (which is when getActivity() should stop returning null) – lyricsboy Jul 31 '12 at 17:18
1

You are right, best option is the second solution here: http://tamsler.blogspot.nl/2011/11/android-viewpager-and-fragments-part-ii.html

so your thoughts are correct.

Frank
  • 12,010
  • 8
  • 61
  • 78