ViewPager + FragmentStatePagerAdapter: necesita saber cuándo se muestra el fragmento (seleccionado)

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 ?

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

    public void onPageSelected(int page) {
      this.currentPage = 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.

preguntado el 31 de julio de 12 a las 15:07

2 Respuestas

You are right, best option is the second solution here:

so your thoughts are correct.

Respondido 13 Feb 13, 08:02

Qué tal esto:

Los programas onPageSelected(int) El método parece que hace lo que quieres.

Respondido 31 Jul 12, 15:07

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

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) - chico de la letra

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.