Interaction between fragments
Click to download source code
In many cases, an activity contains one or more fragments. they collaborate with each other to present a consistent UI to users. In this case, it is very important that fragments can communicate with each other and exchange data.
1. Use the same project created in the previous article to add the TextView id in fragment. xml:
android:id="@+id/lblFragment1"
2. Add a Button in fragment2.xml to interact with fragment1:
3. Add the two fragments to main. xml again:
4. In FragmentsActivity. java, comment out the code added in the previous article and modify it as follows:
@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);/*FragmentManager fragmentManager = getSupportFragmentManager();FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();//WindowManager windowManager = getWindowManager();Display 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 to Fragment2.java to interact 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); // use the getActivity () method to obtain the activity that is currently embedded in the fragment, and then use findViewById () to locate the view Toast contained in the fragment. 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. A message box is displayed. The content of TextView in fragment 1 indicates that the application is successfully obtained ~