Android fragment use (a) basic article restudying

Source: Internet
Author: User

Fragment uses a summary of the basic knowledge points, including the addition of fragment, parameter passing and communication, life cycle and various operations.

Fragment using base fragment to add

Method One: Labels in the layout
Identifier: tag, id, if none, the ID of the container will be used.

Method Two: Add dynamically
Dynamic add takes advantage of a transaction:

 Fragmentmanager Fragmentmanager = getfragmentmanager (); Fragment Fragment = Fragmentmanager. findfragmentbytag (Fragmentb.if (null = = fragment) { Fragmentb FRAGMENTB = new fragmentb (); Fragmenttransaction fragmenttransaction = Fragmentmanager. begintransaction (); fragmenttransaction. add (R.id.tag). commit ();}              

commit()method does not immediately execute the action contained in transaction, but instead adds it to the UI thread queue.
If you want to do this immediately, you can call the Fragmentmanager method immediately after the commit executePendingTransactions() .

commit()The method must be called before the state store, otherwise it throws an exception and can be called if the state is lost commitAllowingStateLoss() . But unless it is a last resort, it is generally not recommended to cover many errors.

Back Stack

Back stack of activity: system maintenance, one back stack per task.
Fragment back stack: The host activity is in charge, one for each activity.

by invocation addToBackStack() , a series of transformations of commit () are stored as a transaction in the back stack,
The user presses the Back key, pops out a transaction from the stack, reverses the operation, and can return to the state before the previous transition.

A transaction can contain multiple operations and is not limited to the same fragment, so each transaction can actually be a series of combinations of operations on multiple fragment.
When you join the back stack, you add this series of combinations as an atom and join it to the return stack.

Construction and parameter passing

All fragment must have one public的无参构造函数 , because the framework often re-creates instances when needed (state recovery), which is what it needs.
If no parameter construction is provided, there will be an exception.

So, 不要给Fragment写有参数的构造函数, 也不要企图搞个什么单例的Fragment these are all anti-design.

Correct posture for parameter passing:

    Public StaticFragmentwithparametersNewinstance(Intnum) {Fragmentwithparameters Fragmentwithparameter =NewFragmentwithparameters (); Bundle args =NewBundle (); Args.Putint (num, num); Fragmentwithparameter.Setarguments (args);return Fragmentwithparameter;}  @Override public  void oncreate (Bundle savedinstancestate) { span class= "kw" >super.getarguments ()! = null? getarguments (). getint (NUM): 0;}        

Here is a static method provided, or the new object can be created after its own set bundle parameters.

Communication of Fragment

In addition to the dialogfragment and nesting fragment need to communicate with their parent fragment, the general fragment is not communicating with any other fragment. Because the requirements should be as independent as possible, modular, reusable.
Fragment has direct communication with its parent activity (except in the case of nesting and dialog, the parent is usually an activity), typically in these three ways:

    1. When constructing fragment, parameters are passed through the bundle.
    2. The parent can directly invoke the public method of fragment, which can also pass some parameters.
    3. Listener, also known as the parent implementation of the callback interface, fragment can be called within their own, where fragment can also pass parameters out.

For Dialogfragment, the outside target can be set in by a public set method.
For example, this method of using fragment: Settargetfragment ()

Example
For nested (nested) Fragment, the communication is similar to the normal Fragment above, except that the parent is not an activity at this time but a Fragment.
There will be a separate article in the back that says the use of nested fragment, please look forward to.

The life cycle of fragment

The life cycle of fragment is first and foremost related to the life cycle of activity,
If activity stopped, none of the fragment can start;
If activity destroyed, all of the fragment will be destroyed.
Only activity in the resumed state, the fragment life cycle can be changed independently, otherwise it is controlled by the activity.

The picture above is from: https://corner.squareup.com/2014/10/advocating-against-android-fragments.html
Here's a more hanging picture: https://github.com/xxv/android-lifecycle

Fragmenttransaction Base operation operation type

There are several actions for fragment in Fragmenttransaction:

attach(), detach()add(), remove(),show(), hide(),replace()

All but the other are in replace() pairs.

Which attach() and detach() not very often.
detach()after the call, fragment actual life cycle will go to Ondestroyview (), but will not go OnDestroy () and Ondetach (), or fragment itself is not destroyed, but the view is destroyed. This is the same as Addtobackstack (), although there is no addtobackstack () when calling detach (), it is still just the stage where the view is destroyed.

add()And remove() is to add and remove fragment.
Remove () is a bit more thorough than detach (), and if you do not join the back stack, remove (), the fragment life cycle will go up to Ondetach ().

show()And hide() is used to set the display and hidden state of the fragment, these two methods do not correspond to fragment state changes, just set the view to visible and gone, and then call the callback of Onhiddenchanged ().

In fact replace() == remove() + add() , so it's anti-operation is also replace (), but the add and remove things to exchange a bit.

For replace () and show (), hide () selection, depending on the actual use of the situation to be determined.
replace()Has the advantage of reducing memory footprint, but returning requires a re-run of the initialization process.
show()and hide() just control the fragment display and hide, will not change the life cycle state, that is, fragment is always in the running state, is kept in memory, suitable for frequent switching situations.

Remove (), if replace () is added to the impact of the back stack on the life cycle

As I said earlier,replace() == remove() + add()
The new fragment will replace the fragment in the container layout, and if not, the new fragment will be added directly.

Whether to add to the back stack has an impact on the life cycle of the fragment.
remove()Or replace() , if commit() not previously called, the addToBackStack() old fragment will be destroyed and detach, i.e. completely destroyed and removed.

If called addToBackStack() , the old fragment will be in the stopped state, called to onDestroyView() , and can be returned by the key to resume.
This time for the old fragment, the member variables are still there, but the view is destroyed. So return it's life cycle from the onCreateView() beginning to rebuild the view.

Resources

Android Reference Fragment
Android Reference fragmenttransaction
Codepath guides:creating and Using fragments

Address of this article:
Android fragment use (a) basic article restudying

Android fragment use (a) basic article restudying

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.