1

So I have been playing around with fragments and I am a big fan of using Log.d to see the output of methods and such to better understand things.

I'm at the point where I'm using findFragmentById.

When I use these Log.d statements:

Log.d("APPTAG", "Fragment: "+ getSupportFragmentManager().findFragmentById(R.id.pager));
Log.d("APPTAG", "Fragment is visible : "+ getSupportFragmentManager().findFragmentById(R.id.pager).isVisible());

I get these results:

APPTAG﹕ Fragment: FragmentTwo{52742bec #1 id=0x7f070077 android:switcher:2131165303:1}
APPTAG﹕ Fragment is visible : true

So the way I understand this is that for a smooth user experience the current fragment as well as the previous and next fragments are created for a smooth transition between them.

I am using this tutorial for setting it all up. I have 3 fragments and only fragment one has a button that calls a method to use the log.d statements.

For those who don't want to look at the link. I'm using a ViewPager and FragmentPagerAdapter to create the fragments.

Question:

  1. Can someone explain to me why am I not getting the values for fragment one?
  2. If possible how can I get them?
  3. Why when at first launch am I getting the values for fragment two (id info and is visible) when fragment one is currently in view/on screen?

Thanks

BluePen
  • 55
  • 7

1 Answers1

0

Can someone explain to me why am I not getting the values for fragment one?

I'm assuming that by "fragment one" you mean the first page in the ViewPager.

Your statement:

getSupportFragmentManager().findFragmentById(R.id.pager)

is returning the fragment for the pager itself, not the page fragments that are inside the ViewPager. Notice the argument that you're passing in to findFragmentById - R.id.pager. That's the id of the pager itself.

If possible how can I get them?

It is possible to get access to the ViewPager's page fragments. One solution is to maintain a collection of the current fragments inside your adapter by overriding instantiateItem() and destroyItem(). There is a full solution here.

Why when I am getting the values for fragment two does it say fragment two is visible when fragment one is currently in view/on screen?

I don't think "Fragment Two" is referring to any page inside the ViewPager - it's referring to the fragment that the ViewPager itself is in.

Community
  • 1
  • 1
JDJ
  • 4,298
  • 3
  • 25
  • 44