Communicating between a fragment and an activity - best practices

后端 未结 9 1308
予麋鹿
予麋鹿 2020-11-22 02:45

This question is mostly to solicit opinions on the best way to handle my app. I have three fragments being handled by one activity. Fragment A has one clickable element th

9条回答
  •  广开言路
    2020-11-22 03:22

    The easiest way to communicate between your activity and fragments is using interfaces. The idea is basically to define an interface inside a given fragment A and let the activity implement that interface.

    Once it has implemented that interface, you could do anything you want in the method it overrides.

    The other important part of the interface is that you have to call the abstract method from your fragment and remember to cast it to your activity. It should catch a ClassCastException if not done correctly.

    There is a good tutorial on Simple Developer Blog on how to do exactly this kind of thing.

    I hope this was helpful to you!

提交回复
热议问题