Android Fragment's life cycle is similar to activity, and may actually involve data transfer, Onsaveinstancestate State preservation, Fragmentmanager management and transaction, Toggle the animation.
let's start with a brief introduction to the life cycle of fragment. In general, you can tell from a name what each life cycle is all about. Appcompatactivity is the subclass of Fragmentactivity, if you want to use fragment, is to inherit fragmentactivity, because of the compatibility problem, We are going to use Getsupportfragmentmanager, and this method is declared in Fragmentactivity. The activity also has a similar method, Getfragmentmanager, two methods return is Fragmentmanager, but one is V4 package. As to the question of how Android is compatible with the fragment version, this is not the case, because the source estimates involved should be many and may be very deep. How does fragment bind its life cycle and activity together? Here's a very critical class: Fragmentcontroller. In the life cycle of the fragmentactivity, the Fragmentcontroller corresponding method is called, and these methods are called to the Fragmentmanager corresponding method. Let's take a look at the OnCreate method of fragmentactivity.
Mfragments.attachhost (null/*parent*/); Super. OnCreate (savedinstancestate);
The Attachhost method is called here, and the Attachhost method calls the Fragmentmanager Attachcontroller method.
Attachcontroller This method is actually going to pass in the Fragmenthostcallback,fragmentcontainer and fragment needed.
Fragmenthostcallback is a subclass of Fragmentcontainer, in fact, it is the activity that fragment to attach, which holds the instance of the activity, the context and the handler. Fragmentcontainer and Fragmenthostcallback are the same instance, which is the activity to be attached. The fragment passed in is null, the parameter name is parent, and the activity is attached, so it is normal to have no parent fragment. When we use Fragmentmanager, if we want to add fragment, it is necessary to write:
Fragmentmanager Manager == manager.begintransaction (); Transaction.add (fragment, Context.getclass (). Getsimplename ()); Transaction.commit ();
Here comes the new class: Fragmenttransaction.
fragmenttransaction is a stack operation for handling fragment, and the specific subclass is Backstackrecord, which is also a runnable. When we call Fragmenttransaction's add, it is actually called the Addop method of Backstackrecord, OP is a custom data structure:
static final class op {op next; Op prev; int cmd; Fragment Fragment; int Enteranim; int Exitanim; int Popenteranim; int Popexitanim; ArrayList <fragment> removed; }
is the data structure of the nodes inside the fragment stack. When we commit, we call Fragmentmanager's Allocbackstackindex, which is used internally by the method to ensure the fragment's normal write order, in fact, Internally, a Backstackrecord ArrayList is used to save the incoming Backstackrecord. After performing fragment writes, the key step is to call Fragmentmanager's enqueueaction and add our operations to the operations queue. When this method is executed, it checks whether the state has been saved, that is, whether it is in the OnStop life cycle, and if so, it will report abnormal information. So we can't do anything about fragment in the onstop of the activity. In order to ensure that the operation is serial, the object lock is also used. The key is to run the Fragmentmanager mexeccommit this runnable, which is mainly to each of the active fragment as a parameter to movetostate this method, Judge the state of fragment. The logic here is more complex, comparing the fragment state to the mcurstate. The state of each fagment at the beginning of a commit is initializing. is divided into 2 cases: 1.mcurstate > state Description fragment start creation. oncreate finally calls the dispatchcreate of Fragmentcontroller and Fragmentmanager and changes the mcurstate state to created, This is also called the Movetostate method, each fragment state is initializing, will begin to read the saved state, and call fragment Onattach,oncreate, respectively, Oncreateview and Onviewcreate. If notIt is setarguments to pass the data before commit, which is unreadable after the commit, because the bundle passed by Setarguments is assigned to fragment when fragment is initialized marguments , and fragment's initialization action is performed in Fragmentmanager Oncreateview. When we use fragment, we commit in the fragmentactivity oncreate, so fragment actually starts initializing at the time of the commit. If you put the setarguments behind commit, there is no chance of passing it to fragment. Here we should note that the above is done in the fragmentactivity OnCreate, that is, the activity is not created at this time, so the resources about the activity is not available here. 2.mcurstate < state Description fragment has been created. So, fragment real and activity bindings are at the time of commit invocation. Official recommendation we pass setarguments to the parameters required to construct the fragment, it is not recommended to pass the parameters directly through the construction method, because when the screen is switched, the new activity is recreated, That is, re-creating the new fragment, the original data will be lost, but the bundle passed by setarguments will be preserved. We just look at Fragmentactivity's OnCreate method and know that it will determine if the previous configuration and savedinstancestate are NOT NULL, And Savedinstancestate will save the fragment data, which is stored in parcelable form, which is fragmentmanagerstate, and if not NULL, the data is reloaded. Actually, the graph of the life cycle above is problematic, onactivitycreated is actually called in the onstart of Fragmentactivity, when mcurstate becomes activity _created,While the state of fragment becomes created, if fragment is not declared in the layout file, the use of dynamic addition, then fragment is here to call Oncreateview and onviewcreated, and add the fragment to the fragmentactivity layout. First of all we must be clear that, when onstart, activity although visible, but has not yet shown to the foreground, so this time only to deal with the dynamic add fragment case is reasonable, If we put the dynamic add fragment logic in the OnCreate, when the activity itself layout has not yet created, how can we find container loading fragment? This also reminds us not to deal with time-consuming logic in fragment's Oncreateview and onviewcreated, otherwise it will affect fragmentactivity display to the foreground. When fragmentactivity into the Onresume, has been shown to the foreground, this time send a message to handler, notify Fragmentmanager, When the mcurstate becomes resumed, the fragment will start to set up the listener events and so on. When Fragmentactivity enters OnPause, it will first check if fragment has not set the listener event, if not, let it set, then modify Mcurstate to started, This is the second case in the front, fragment into the OnPause. When fragmentactivity enter OnStop, first notice Fragmentmanager modify mcurstate for stopped, then will notify fragment into OnStop, Then is the handler received the message, notify Fragmentmanager will mcurstate changed to activity_created, notify fragment call Performreallystop, that is, the real end. When Fragmentactivity enters OnDestroy, it will confirm whether it is really reallystop, then notify Fragmentmanager to repairChange Mcurstate to CREATED, at this time fragment state is activity_created, start saving view data, call Ondestroyview, parent layout begins to remove fragment. Look closely at this logic, you will find that whether or not set fragment is required to keep, will enter the Ondetach, indicating that the fragment and fragmentactivity are no longer related. Let's take a look at the Onretainnonconfigurationinstance method, which sets the fragment mretaining to True, This will make fragment will not enter the OnDestroy, is to re-create a new fragmentactivity, but also just clear fragment mhost,mparentfragment, Mfragmentmanager and Mchildfragmentmanager, the previous data will be saved, and the fragment is not destroyed, This causes a problem: the re-created Fragmentactivity itself creates a new fragment, so there is a fragment overlap, because fragment's status is stopped, and OnStart and Onresume are respectively entered , which is the process of re-displaying to the foreground. We will find in the actual test that, in the case of no processing, the fragment in Fragmentmanager is more and more, so in fact, considering this situation: if the application is killed in the background, restart the application, The previous fragment may overlap the interface. This is a hassle when it comes to tab, because tab is a few fragment at the foreground, and if the activity is killed and recreated, the first fragment is entered. But if it is killed under another fragment, it could cause the two fragment to overlap. So you can determine in oncreate whether or not to recreate the activity, as long as the savedinstancestate is NULL, if NULL, the activity has not been rebuilt. Fragment can be added, even if the tab above the case can also be processed, as long as not add the first fragmenT will be. if it is based on such a judgment to solve this problem, we can also add fragment, specify an ID or tag, determine whether the corresponding ID in Fragmentmanager or the fragment of the tag is present to determine if you want to add. of course, if there is no need for the project, we can force the vertical screen. If you are only switching between the two screens, there is another solution, set in the Activity tab in AndroidmanifestAndroid:configchanges= "Orientation|keyboardhidden", but this attribute is invalid on Android 4.0, it must be written like this: android:configchanges= " Orientation|keyboardhidden|screensize ". In this way, when the screen switch, will not go onretainnonconfigurationinstance, walking is onconfigurationchanged, switch will not destroy the current fragmentactivity, Natural fragment can also be kept down. If we want to add cut-out animations for fragment, there are two ways to do this for V4 and non-V4. 1. For V4, the view Animation is used, and the animation resources are placed in the res\anim\ directory. 2. For non-V4, use property animations, and animate resources in the Res\animator\ directory. Generally we use V4 fragment, and the view animation is sufficient to meet our requirements for transition animations. Let's take a look at Fragmenttransaction's Addtobackstack method. If we want to achieve this effect: Click the Back button and return to the previous fragment. Then you have to call the Addtobackstack method. This method requires passing in a string parameter, in fact we just pass in null on the line, if we do not want to specify the stack (although the stack, is actually just a ArrayList, and does not implement the structure of the stack) name. Carefully look at the source code, we will find that if you do not call this method, when pressing the return key, the direct finish of the current fragmentactivity. fragment's fallback and activity fallback is very different, we know, fragment operation is Fragmenttransaction, And Backstackrecord is really the implementation of the specific subclasses of these operations. Then the question is: if we are two times Fragmenttransactiont add fragment, add a for the first time, add B and C for the second time, we will not returnIs fragment, is Backstackrecord op, and op is recorded in each operation of the fragment, when we go back to the second operation, is the second addition of B and C are exited. If we have only one fragment, and do not want to implement fragment's fallback stack, do not call addtobackstate, otherwise, when the activity presses the return key, does not immediately exit the activity, but returns a blank, because even if it is null, it is added to the ArrayList of Backstackrecord, because this parameter is labeled as Mname Backstackrecord, in the actual processing, Whether it is null is not important at all. Of course, we can also call Fragmentmanager's Popbackstack method to do the fallback stack operation, if we want to execute immediately, we should call the Popbackstackimmediate method, In fact, this method is called by default. If we add fragment, we do not set any tag, but in the pop-up stack, ask to pop up the latest fragment, add new fragment. fragment stack is not as complex as the activity stack, providing a variety of startup modes, if you look at the source, you will find that It's actually just one: pop up all the fragment in the nearest Backstackrecord. If we call Popbackstack, do not specify flag as pop_back_stack_inclusive, the implementation of the source code is divided into two kinds of judgment with If-else, But the actual processing is similar, but not specified, it will deal with the more troublesome, if possible, we still specify. Back to the question above us, how do we do it? replace does not affect the fallback stack, if we really want to replace a fragment with replace, and want to implement a fallback stack, it is necessary to addtobackstack, But if we want to replace a fragment at this point, the records in the fallback stack will not be replaced, that is, when we choose to fallback, we will return to the fragment we have replaced, so we have to eject the fragmen before we replace it.T. fragmentmanager provides a Getbackstackentrycount method that tells us the number of fallback stacks, There are getbackstackentryat methods to get to the corresponding Backstackrecord, then we can do the following to implement the popup:
if (Manager.getbackstackentrycount () >0 int n = Manager.getbackstackentrycount (); Manager.popbackstack (Manager.getbackstackentryat (n -1). GetName (), fragmentmanager.pop_back_stack_inclusive);}
Then we can use replace. We must note that Add,remove and replace affect the display of fragment on the interface, they have nothing to do with the fallback stack, in fact, if we do not call Addtobackstack, Even there is no fallback stack, and the fallback stack is added after each invocation of the method, whether or not it is repeated, it will not make any judgment, so if Fragmenttransaction commits more than one fragment at a time, But just call Addtobackstack once, although there are multiple fragment on the interface, but there is only one record in the fallback stack. fragment said to the end, in the source view, just and the activity life cycle of the view, it is impossible to do with the activity as complex functions, its logic business code, actually also belongs to the activity , just move to another class, of course, if you like, even if you think of it as a lightweight viewcontroller is also possible, after all, it is responsible for the view of all the business functions. fragmenttransaction provides several operations for fragment Add,remove,hide,show and replace, and we want to be aware of the difference between add and replace. replace is actually a combination of remove + add, and with replace, each switch will cause fragment to be recreated because it removes the replaced fragment from the view. This will be re-created when the replacement comes back. Such frequent switching can seriously affect performance and traffic. So the official argument is that the replace () method is simply a simple way to use the last fragment when it is no longer needed. The correct way to switch is add (), hide (), add () another fragment when switching again, just hide () and show () another. Of course, before hide, we need to isadd to see if we've added it. If you switch with hide and show, we don't need to save the data becauseFor fragment is not destroyed, if it is replace this way, we have to save the data, for example, if there is edittext in the interface, if we want to save the input before the edittext, we need to save this value, or use Replace, Will remove the entire view. fragment also involves communication with the activity and other fragment. The best way is to just let activity and fragment communicate, if fragment want to communicate with other fragment, but also through activity. We can use the callback fragment method to communicate, of course, can also be declared in the fragment interface, as long as the activity implementation of these interfaces, can achieve activity and fragment communication. think of setarguments as a bundle to preserve the data, so can we use this to make a little article on the pass? in software design, in order to reduce dependency, it is proposed to use a high-level abstraction to take charge of communication between components, so that there is no need to rely on each other, that is, the so-called dependency inversion principle. So, can we use this principle to do something about it? The performance of dependency inversion in many frameworks is to take the form of annotations, and we can consider the way that annotations are used to solve this problem. If the parameters are only for the purpose of building fragment, the problem is relatively simple, so long as the reflection is reasonably used, we can obtain the Fragment field and assign the value. similar forms of expression are as follows:
classFragmentaextendsfragment{@ArgPrivate intAge ; Public voidonCreate () {Fragmentinject.inject ( This); }}classActivityaextendsactivity{ Publicvoi onCreate () {Fragmenta a=NewFragmenta (); Bundle Bundle=NewBundle (); Bundle.putstring ("Text", "Hello"); A.setarguments (bundle); Fragmentmanager Manager=Getsupportfragmentmanager (); Fragmenttransaction Transaction=manager.begintransaction (); Transaction.add (R.id.container, a); Transaction.commit (); }}In fact, this is nothing more than a change in the way the code is organized, because we can get bundles in the fragment oncreate, and we can do the same thing in the same way, and the total code will be less, but if you just look at it from fragment, We only need to call the Fragmentinject.inject method and declare arg annotations, other things do not consider, the relevant parsing bundles and field assignments are placed in the abstract fragmentinject, we do not have to write the same code for each fragment, as long as the FRA Gmentinject on the line. Of course, the above is just a simple implementation, really is to achieve a mature thing is to consider a lot of aspects, we here put this simple project on GitHub: Https://github.com/wenjiang/FragmentArgs.git, if there are new ideas, welcome to add.
Android Fragment parsing and using