The communication between fragment and activity is as follows: 1. Provided by the initialization Function
1. In the process of dynamically adding fragment, we provide data for fragment through the fragment. setarguments () method in the activity;
2. In fragment, the onattach () function obtains a bundle object by calling getarguments () to obtain the data we provide. Ii. Create callback Interfaces
For example, in news browsing, there are two fragment items: one is used to display news titles and the other is used to display news content. When we click the news title, the news content is displayed in another fragment. Next we will transmit a message to fragment2 by pressing the button in fragment1.
First, we need to create a callback interface in fragment1, re-write its method in the activity, and pass the information to fragment2 (we can also pass the information to other fragment ).
1. Create a callback interface;
public interface OnButtonClickListener {public void onButtonClicked();}
2. To ensure that the host activity implements this interface, the onattach () method of fragment1 needs to forcibly convert the incoming activity type and instantiate an onbuttonclicklistener object;
@ Overridepublic void onattach (activity) {log. V (TAG, "fragment1 onattach"); bundle ARGs = getarguments (); If (null! = ARGs) {// here we can save the data received from acivity and display it to fragment. Try {mlistener = (onbuttonclicklistener) activity;} catch (classcastexception e) {Throw new classcastexception (activity. tostring () + "must implement onbuttonclicklistener");} super. onattach (activity );}
3. register the Click Event of the button and call the callback method in the event.
@ Overridepublic view oncreateview (layoutinflater Inflater, viewgroup container, bundle savedinstancestate) {log. V (TAG, "fragment1 oncreateview"); view = Inflater. inflate (R. layout. fragment1, container, false); // registers the event for the button and calls the callback interface to return the information to the upper view. findviewbyid (R. id. fragment1_btn ). setonclicklistener (New onclicklistener () {@ overridepublic void onclick (view v) {mlistener. onbuttonclicked () ;}}); Return view ;}
Then, the code of the activity should be implemented:
1. Implement the callback interface through implements;
Public class mainactivity extends fragmentactivity implements onbuttonclicklistener {
2. Rewrite the callback method and pass data to fragment2.
@ Overridepublic void onbuttonclicked () {log. I (TAG, "onbuttonclicked"); textview TV = (textview) fragment2.getactivity (). findviewbyid (R. id. fragment2_ TV); TV. settext (TV. gettext () + "\ n receives data from fragment1! ");}
3. Download source code
Reference: http://www.cnblogs.com/getherBlog/p/3949171.html
Code download link: http://www.apkbus.com/android-179360-1-1.html
Fragment communicates with acitment