When using fragment, there is always a problem, that is, the communication between fragment and activity. Here's a record of how activity and fragment communicate with each other by implementing interfaces.
1. The activity sends a communication to the fragment, which reads:
Private Onmainlistener Mainlistener; Binding interface
@Override
public void Onattachfragment (Fragment Fragment) {
try {Mainlistener = (Onmainlistener) fragment; } catch (Exception e) {throw new ClassCastException (this.tostring () + "must implement Onmainlistener"); }
Super.onattachfragment (fragment); }//interface
Public interface Onmainlistener {public void onmainaction (); }
- Onmainaction method is the activity to fragment communication method, inside can put parameters, in the place to send the communication directly call the method.
Copy Code
- In the corresponding fragment to write this:
Copy Code
public class Myfragment extends Fragment implements Onmainlistener {
public void Onmainaction () {
Here is the interface for implementing communication
2. Fragment communication to the activity: (similar to the previous)
- Private Onfragmentlistener Mlistener;
@Override public void Onattach (activity activity) {
Super.onattach (activity);
try {Mlistener = (onfragmentlistener) activity;
} catch (ClassCastException e) {
throw new ClassCastException (activity.tostring () + "must implement Onfragmentlistener");
}
}
Public interface Onfragmentlistener {public void onfragmentaction (int flag); }
Implementing interfaces in activity: Public class mainactivity extends Activity implements Onfrag mentlistener{
..................
public void onfragmentaction (int flag) {
Both are communicated through the implementation of the interface, the important place is the interface binding in the Onattachfragment and Onattach methods respectively. Communication and other methods, such as broadcasting, static handler, and so on, here will not repeat.
end~
Http://www.colabug.com/thread-1124396-1-1.html
Fragment and his own activity newsletter.