Example code of mutual communication between Android fragment and activity
Communication between Android fragment and activity
preface
Since Android 3 0 after the introduction of fragment, it is mainly to support dynamic and flexible interface design and screen adaptation. Fragment cannot exist alone. It must rely on activity as a part of the view display. It has its own life cycle, receives its own events, and has more flexible characteristics. Now fragment has been widely used in app development. The most common mode is single activity and multiple fragments. Fragment depends on activity, so it is inevitable to interact with activity. Here we briefly introduce three common interaction methods.
1、 Interface mode
Define an interface in the fragment class and implement it in the activity. Fragment gets the concrete implementation object of the interface in the onattach() callback function. Later, the fragment can call the methods in the interface to communicate with the activity.
On Android 5 After 0, the onattach (activity) method was abolished and onattach (context) was used instead, that is, the passed parameters changed
This interface needs to be implemented in the activity
2、 Broadcast
Register the broadcast receiver in the activity and send the broadcast in the fragment
3、 Fragment gets data from activity
Set the parameter setarguments () in the getInstance () method of fragment
And then get it through the getarguments () method
Thank you for reading, hope to help you, thank you for your support to this site!