1. Define an internal interface in fragment, in the fragment initialization method, convert the parent activity to this interface, assign the value to the member variable
Public classDummyfragmentextendslistfragment {Someeventlistener listener; Public InterfaceSomeeventlistener { Public voidOnsomeevent (intArg); } @Override Public voidOnattach (activity activity) {Super. Onattach (activity); Try{Listener=(Someeventlistener) activity; } Catch(classcastexception e) {Throw Newclasscastexception (activity.tostring ()+ "must implement Someeventlistener"); } } ...}
2. Parent activity must implement this interface
Public Static class extends Activity Implements Dummyfragment.someeventlistener { ... Public void onsomeevent (int arg) { // parameters are passed in, And then call each fragment method here to pass the message }}
3. In the corresponding event method of fragment, the calling interface notifies the parent activity
@Override publicvoidintlong id) { // Send the event to the host activity listener.onsomeevent (position); }
3. In the parent activity, after getting each fragment, call the corresponding fragment method in the interface method
Public Static classMainactivityextendsActivityImplementsDummyfragment.someeventlistener {... Public voidOnsomeevent (intArg) { //parameters are passed in, and then the various fragment methods are called here to pass the message.Articlefragment Articlefrag =(articlefragment) Getsupportfragmentmanager (). Findfragmentbyid (r.id.article_fragment); if(Articlefrag! =NULL) {Articlefrag.updatearticleview (position); } Else{articlefragment newfragment=Newarticlefragment (); Bundle args=NewBundle (); Args.putint (Articlefragment.arg_position, POSITION); Newfragment.setarguments (args); Fragmenttransaction Transaction=Getsupportfragmentmanager (). BeginTransaction (); Transaction.replace (R.id.fragment_container, newfragment); Transaction.addtobackstack (NULL); Transaction.commit (); } }}
In fact, the entire mechanism, is the activity in the creation of these fragment, as a member of the fragment variables, in the fragment when the change, can be notified by the agreed interface method, these agreed interface methods are defined by the fragment, Implemented by the activity.
Message passing between Android fragment