Use the EventBus framework to implement Fragment and Activity communication, and eventbusfragment
When I first learned about Android, communication between Fragment and Activity has always been a headache.
The so-called communication is actually to share (or vice versa) Some Member information in the Activity with Fragment ). One method is to use the callback interface. An interface defined in Fragment is implemented by the Activity. After obtaining the Activity instance in Fragment, It is forcibly converted to the interface type, and then calls back the interface as needed to complete communication. This is abstract. The following is an example:
AFragment:
// Define an Interface
public interface Callback{ void onUpdateUI();}
BActivity implementation interface:
Public class BActivity extends Activity implements BFragment. Callback {// omitting the code @ Override public void onCommunicate () {// implement communication content }}
Call back the interface in Fragment to implement communication:
Callback callback = (Callback) getActivity();callback.onCommunicate();
This completes a communication. In addition to the interface method, you can also achieve the same effect through broadcast, which is not described here.
However, these methods have a problem, which is complex and increases the coupling between the Activity and Fragment.
To solve this problem, the event bus framework emerged. There are many such frameworks. Here we only talk about EventBus.
The event bus is based on the observer mode. If you understand this design mode, you will better understand the use of EventBus.
Add dependency in gradle:
compile 'org.greenrobot:eventbus:3.0.0'
First, define an event type. This event is the carrier for subsequent communication on various interfaces:
public class MyEvent { private String msg; public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; }}
Register the subscriber in the interface:
EventBus.getDefault().register(this);
Add the subscription event action in the interface:
@ Subscribe (threadMode = ThreadMode. MAIN) // here, the annotation specifies that the operation is performed in the MAIN thread public void onMyEvent (MyEvent event) {// Operation event}
The last is the release event. After the event is published, all subscribers will receive the event (execute the subscription action previously added ):
MyEvent event = new MyEvent (); //... sets eventEventBus. getDefault (). post (event );
With this method, as long as a subscriber is registered in Activity/Fragment and a subscription action is added, the communication can be formed by publishing events elsewhere. This reduces the coupling between Activity and Fragment.