0

I have some fragments that I need to run some animations when they get visible.

Those fragments are inside a ViewPager. Thanks to that answer - How to determine when Fragment becomes visible in ViewPager - I know that I get notified when my fragment is visible by the method getUserVisibleHint.

Because I have a lot of animations, I made custom views that know how to animate itself. And now I need to notify all the views inside the fragment in the method getUserVisibleHint of the fragment to they know that is time do animate themselves.

So my question is: How can I notify all the views inside a fragment?

Any solution is welcome, but how I said, the views that I need to notify are custom views created by me, so I believe that I need some kind of custom notification too.

Community
  • 1
  • 1
jonathanrz
  • 4,206
  • 6
  • 35
  • 58

1 Answers1

1

You said all your views are custom. I'm assuming they all implement a specific interface (lets say, InterfaceA).

The following code will call the notificationMethod() on every custom view that implements your InterfaceA interface. The viewGroup is your root view (for example, a LinearLayout).

int childcount = viewGroup.getChildCount();
for (int i=0; i < childcount; i++){
   View view = viewGroup.getChildAt(i); 
   if (view instanceof InterfaceA) { 
       ((InterfaceA)view).notificationMethod();
   }
}
jonathanrz
  • 4,206
  • 6
  • 35
  • 58
Brian Attwell
  • 9,239
  • 2
  • 31
  • 26
  • 3
    I would suggest instead of a direct cast: `View child = viewGroup.getChildAt(i); if (child instanceof InterfaceA) { ((InterfaceA)child).notificationMethod();`. That way it will continue gracefully if there are any views in the layout that do not implement the interface. – Kevin Coppock Aug 17 '13 at 03:53