Here I will not go into details about the conventional writing methods, such as static variables, static methods, persistence, application global variables, and sending and receiving broadcasts.
First, we will introduce how to use Handler to implement the interaction between Fragment and Activity.
Step 1: Define a method in Activity to set the Handler object.
Public void setHandler (Handler handler ){
MHandler = handler;
}
Step 2: Obtain the Activity of the Fragment in the callback function onAttach () in Fragment, call the setHandler method, and set Handler. This Handler is defined in Fragment to receive messages and interact with Fragment.
@ Override
Public void onAttach (Activity activity ){
Super. onAttach (activity );
MActivity = (MainActivity) activity;
MActivity. setHandler (mHandler );
}
Public Handler mHandler = new Handler (){
Public void handleMessage (android. OS. Message msg ){
Switch (msg. what ){
Case 1:
Text. setText (String) msg. obj );
Break;
}
};
};
Then, we can send a message in the Activity to the Hanlder In the Fragment for interaction.
Public void inter (View view ){
Message msg = new Message ();
Msg. obj = edit. getText (). toString ();
Msg. what = 1;
MHandler. sendMessage (msg );
}
I wrote a Demo to share with you, Link: http://download.csdn.net/detail/huangyabin001/7559807
Click to download demo