Interacting between fragments
Click to download the source code
Many times, an activity contains one or more fragments, which collaborate with each other to present a consistent UI to the user. In this case, it is important for the fragments to communicate and exchange data between them.
1. Add TextView ID in fragment.xml using the same project created in the previous article:
Android:id= "@+id/lblfragment1"
2. Add a button in Fragment2.xml to interact with Fragment1:
<button android:id= "@+id/btngettext" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" android:text= "Get text in Fragment #1" android:textcolor= "#000000"/>
3. Add two fragments back to the Main.xml:
<fragment android:id= "@+id/fragment1" android:name= "Net.zenail.Fragments.Fragment1" android: Layout_width= "0px" android:layout_height= "match_parent" android:layout_weight= "1"/> < Fragment android:id= "@+id/fragment2" android:name= "Net.zenail.Fragments.Fragment2" android:layout_ Width= "0px" android:layout_height= "match_parent" android:layout_weight= "1"/>
4. In Fragmentsactivity.java, comment out the code added in the previous article, modified as follows:
@Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.main);/*fragmentmanager Fragmentmanager = Getsupportfragmentmanager (); Fragmenttransaction fragmenttransaction = Fragmentmanager.begintransaction ();//windowmanager WindowManager = Getwindowmanager ();D isplay Display = Windowmanager.getdefaultdisplay (); if (Display.getwidth () > Display.getheight ()) {//fragment1 fragment1 = new Fragment1 (); Fragmenttransaction.replace (Android. R.id.content, fragment1);} else {//fragment2 Fragment2 = new Fragment2 (); Fragmenttransaction.replace (Android. R.id.content, Fragment2);} Fragmenttransaction.commit (); */}
5, add the following code in Fragment2.java, to achieve the interaction with Fragment1:
@Overridepublic void OnStart () {//TODO auto-generated method Stubsuper.onstart (); Button Btngettext = (button) getactivity (). Findviewbyid (R.id.btngettext); Btngettext.setonclicklistener (new View.onclicklistener () {@Overridepublic void OnClick (View v) {//TODO auto-generated method Stubtextview lbl = (TextView) Getactivity (). Findviewbyid (r.id.lblfragment1);//Through the Getactivity () method to obtain the currently embedded fragment of the activity, and then use the Findviewbyid () Locate the view contained in the Fragment Toast.maketext (Getactivity (), Lbl.gettext (), Toast.length_short). Show ();});}
6. Press F11 to debug the application, click the button in the second fragment on the right, and you can see the popup message box, which is the content of TextView in fragment 1, indicating success ~