2

I have a ViewPager with several fragments using FragmentStatePageAdapter.

I'm looking to implement something that will allow me to send a string of data that is entered into an EditText from a fragment to an activity when the user swipes away from the fragment.

I've looked at OnPageChangeListener and tried a couple of different things with that but as onPageSelected gives you the fragment id of the one you're moving onto I can't get the Layout View of the fragment to reference the EditText I'm swiping away from. There will also be no set fragment that leads on to another i.e. Fragment 1 doesn't always lead to Fragment 2 etc.

I tried using the onDestroy() of the fragment but that doesn't seem to be called until I've swiped 2 fragments away so that's no use either.

Does anyone have any suggestions as to what I could use to achieve this?

Thanks

KT79
  • 89
  • 1
  • 2
  • 10
  • 1
    Are you using a FragmentStatePagerAdapter for your ViewPager? I imagine that class will have some kind of `getPosition()` function. – AdamMc331 Dec 18 '15 at 15:45
  • 1
    Relevant enough, but not sure if it's duplicate. Check this out: http://stackoverflow.com/questions/8258759/getting-the-current-position-of-a-viewpager – AdamMc331 Dec 18 '15 at 15:46
  • @McAdam331 yes using a FragmentStatePagerAdapter. I can get the current position no problem when I'm on the fragment, I guess my issue is that I need to store this somewhere before the onPageSelected is called and then pass it through but without the user interacting with a button or such like. Does that make sense? Not sure I can use onAttach() or onResume() as to me it seems these will already have been invoked as part of the FragmentStateAdapters function, much as how the onDestroy doesn't get called until after 2 swipes? – KT79 Dec 18 '15 at 15:56
  • Did you see the other post I linked to? Perhaps you can create a custom interface to track the last position/current position someone has visited? – AdamMc331 Dec 18 '15 at 15:57
  • 1
    @McAdam331 ah sorry hadn't saw that while I was typing out my ramble, will check it out thanks :) – KT79 Dec 18 '15 at 15:59
  • I've implemented the marked answer from your suggestion but it returns zero every time, likely something I'm doing wrong but puts me on the right track I think. – KT79 Dec 18 '15 at 16:41

1 Answers1

0

Try remembering each fragment's id on each onPageSelected(). Once the fragment is selected, you remember its id. Once the other one is selected, you check the remembered id just before you update it.

Yury Fedorov
  • 14,508
  • 6
  • 50
  • 66
  • can you expand on this a bit more? At what point will you remember the fragment and would you use the viewpager.getcurrentitem() > – KT79 Dec 21 '15 at 18:01