07(3)

1. What is debris

Fragment (Fragment) is an active fragment may be embedded among the UI, and it makes the process more rational use of space sufficiently large screen, on the plate and thus a very wide application. Although the debris for you should be a new concept, but I believe you should learn it effortlessly, and activities because it is too much like, can contain the same layout, the same has its own life cycle. You can even be understood as a mini debris activities, although this mini-activities possible and normal activities are as large.

2, the debris of use

  1. Creating the debris instance to be added.
  2. Get to FragmentManager, in the event you can call directly getFragmentManager () method to get.
  3. Open a business, opened by calling beginTransaction () method.
  4. Fragment was added into the container, typically using replace () method implementation, need to pass debris container id and instance to be added.
  5. Commit the transaction, call the commit () method to complete

3, the analog return stack debris

After we successfully achieved to add pieces to the activities dynamic function, but you try you will find by clicking on the button to add a fragment, then press the Back button will exit the program. If we want to emulate here is similar to the return stack effect, press the Back button to return to the previous debris, how to achieve it?

Actually very simple, FragmentTransaction provides a addToBackStack () method can be used to add a transaction to the return stack, modify the code in MainActivity

Communicate 4, fragments and activities

  Although fragments are embedded display at the event, but in fact their relationship is not so close. As you can see, fragments and activities are present in each of them a separate class, and not so obvious way to direct communication between them. If you want to debris in the method invocation at the event, or activity in the method call in the debris, how to achieve it? In order to facilitate communication between the fragments and activities, FragmentManager provides a method similar to the findViewById () is dedicated to obtain fragments from Examples layout file, the code is as follows: RightFragment rightFragment = (RightFragment) getFragmentManager () findFragmentById. (R.id.right_fragment);

Call FragmentManager of findFragmentById () method, they can get an instance of the corresponding fragments at the event, then you can call the debris in the way easily. Mastered the method how to call in the debris at the event, then how should we call activity in the way to do that in the debris? This fact is more simple, and can be used to obtain active fragments of the present example is associated, as shown in each of the code fragments by calling getActivity () Method: MainActivity activity = (MainActivity) getActivity ();

 

 

 

Guess you like

Origin www.cnblogs.com/1014040868lyn/p/11722834.html
073
073