Now I'm going to do a little demo of communication between fragment and fragment.
- Set up two fragment, then add 1 buttons and one textview each.
- Click the Fragment1 button to modify the TextView text in the Fragment2.
- Similarly, click the button inside the Fragment2 to modify the Fragment1 TextView text.
Pre-preparation: Put two fragment:1 and 2 in the activity, and then bind the view for each one.
publicclass Fragment1 extends Fragment { publiconCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { null); return rootView; }}
The operation is like this:
Add TextView and buttons to all two XML files
The next step is to find the button response events, written in the Java files of Fragment1 and Fragment2:
Fragment1
Public class Fragment1 extends Fragment { PrivateTextView TV1;PrivateButton button1;@Override PublicViewOncreateview(Layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {View Rootview = inflater.inflate (R.layout.fragment1,NULL); Button1 = (Button) Rootview.findviewbyid (R.id.button1);//ButtonTV1 = (TextView) Rootview.findviewbyid (R.ID.TEXTVIEW1);//TextButton1.setonclicklistener (NewView.onclicklistener () {@Override Public void OnClick(View v) {System.out.println ("In Fragment1 Response click button Event");//Get the activity attached to the current fragment and get Fragment2.Fragment2 Fragment2 = (Fragment2) getactivity (). Getfragmentmanager (). Findfragmentbyid (R.id.fragment2); Fragment2.settext ("The content has changed ..."); } });returnRootview; } Public void SetText(String text) {//Define a method for modifying text contentTv1.settext (text); }}
Fragment2
Public class Fragment2 extends Fragment { PrivateTextView TV2;PrivateButton button2; PublicViewOncreateview(Layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {View Rootview = inflater.inflate (R.layout.fragment2,NULL); Button2 = (Button) Rootview.findviewbyid (R.id.button2);//ButtonTV2 = (TextView) Rootview.findviewbyid (R.ID.TEXTVIEW2);//TextButton2.setonclicklistener (NewView.onclicklistener () {@Override Public void OnClick(View v) {System.out.println ("In Fragment2 Response click button Event"); Fragment1 fragment1 = (Fragment1) getactivity (). Getfragmentmanager (). Findfragmentbyid (R.ID.FRAGMENT1);//Get the activity attached to the current fragment and get fragment1.Fragment1.settext ("The content has changed ..."); } });returnRootview; } Public void SetText(String text) {Tv2.settext (text); }}
Look at the simulator.
Click button 1:
Click button 2:
This is a little exercise that I learned in fragment. Please forgive my garbled, this question I also took the time to get, temporarily did not find the problem, if there is great God know can comment teach me! Thank you very much!
Communication between two simple fragment