When fragment is used, there is always a problem, that is, communication between fragment and activity. Next we will record the methods for communication between activity and fragment through implementation interfaces.
1. The activity sends a message to fragment, which is written as follows:
Private OnMainListener mainListener;
// Bind the interface
@ Override
Public void onAttachFragment (Fragmentfragment ){
Try {
MainListener = (OnMainListener) fragment;
} Catch (Exception e ){
Throw newClassCastException (this. toString () + "must implementOnMainListener ");
}
Super. onAttachFragment (fragment );
}
// Interface
Public interface OnMainListener {
Public void onMainAction ();
}
The onMainAction method is the method by which the activity sends a message to fragment. You can put parameters in the method and directly call the method where the message is to be sent.
Write this in the corresponding fragment:
Public class MyFragment extends Fragment implementsOnMainListener {
........................
@ Override
Public voidonMainAction (){
// Here is the communication interface
}
2. fragment sends a message to the activity: (similar to the previous one)
Private OnFragmentListener mListener;
@ Override
Public void onAttach (Activity activity ){
Super. onAttach (activity );
Try {
MListener = (OnFragmentListener) activity;
} Catch (ClassCastException e ){
Throw newClassCastException (activity. toString () + "must implement OnFragmentListener ");
}
}
Public interface OnFragmentListener {
Public void onFragmentAction (intflag );
}
Implement interfaces in activity:
Publicclass MainActivityextendsActivityimplementsOnFragmentListener {
..................
// Interface Implementation Method
@ Override
Public voidonFragmentAction (int flag ){
// Communication Interface
}
Both of them communicate through the implementation of interfaces. The important thing is to bind interfaces in the onAttachFragment and onAttach methods respectively.
There are other communication methods, such as broadcast and static handler, which will not be described here.
End ~