-2

I have Activity with ViewPager. There is a button in the Activity that should change it's visibility depending on which item (fragment) is shown on the screen.

Problem: I can't access the button from within fragment because findViewById() call returns null when invoked from the inside of fragment code. I also thought I could notify activity about fragment state change but the code from the documentation is already deprecated.

Question: How to change a button within an activity when a particular fragment appears/disappears on the screen?

Note: Getting a current fragment is not a problem. I need to detect that fragment is changed.

Sasha Shpota
  • 9,436
  • 14
  • 75
  • 148
  • You can get the Activity's view inside a Fragment. I suppose this is what you want to do. Is it? – Ümañg ßürmån Sep 29 '18 at 18:54
  • Possible duplicate of [Getting the current Fragment instance in the viewpager](https://stackoverflow.com/questions/18609261/getting-the-current-fragment-instance-in-the-viewpager) – Jeel Vankhede Sep 29 '18 at 19:42
  • @UmangBurman unfortunately `getActivity().findViewById(id)` returns null, otherwise I would not open this question. – Sasha Shpota Sep 29 '18 at 20:13
  • @JeelVankhede getting the current fragment has never been a problem, but I need **to detect that the fragment has changed**. – Sasha Shpota Sep 29 '18 at 20:14
  • It's the same thing, you can detect that from `addOnPageChangeListener()`. I marked it duplicate because of this only. – Jeel Vankhede Sep 29 '18 at 20:22
  • **Please explain why voting down.** – Sasha Shpota Sep 29 '18 at 20:22
  • Thank you. I'm not quite sure why it is the same. I am actually asking about detecting fragment change and not about getting current fragment. I guess using `addOnPageChangeListener` is just one of the ways of implementing "current fragment" functionality. Among 28 answers there is only one that touches `addOnPageChangeListener` and I can hardly imagine how it relates to my question. Though @CommonsWare has provided perfect solution. – Sasha Shpota Sep 29 '18 at 20:40

1 Answers1

2

Create a subclass of SimpleOnPageChangeListener inside your activity (e.g., as an anonymous inner class). In that subclass, override onPageSelected() and update the button visibility based on the selected page index. Then call addOnPageChangeListener() on your ViewPager, supplying an instance of the SimpleOnPageChangeListener subclass.

Now, on every page change in the pager, onPageSelected() will be called, and you can update the button visibility based on the page.

Sasha Shpota
  • 9,436
  • 14
  • 75
  • 148
CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491