Android Internship notes (4)---Fragment (fragmentation) Basic concept analysis

Source: Internet
Author: User

Android Internship notes (4)---Fragment (fragmentation) Basic concept analysis

Reprint Please specify source: Coder-pig

Fragment believe that everyone will be unfamiliar, slide, drawer effect, dialogfragment ah, and so on, a lot of places will

Used to fragment, for the basic concept of fragment in the previous article has actually given, here review again,

Warm so know new well, combined with Google's official API to review!


1) What is the fragment and its life cycle:




Core points:

1) after version 3.0 introduced, namely MINSDK to be Greater than one

2) Fragment needs to be nested within the activity , and of course it can be nested into another Fragment , but this is nested

fragment also need to be nested in the activity, and indirectly, fragment still need to be nested in the activity! by host

life cycle impact of activity , of course he also have a life cycle of their own ! In addition Not recommended inside the fragment . Nesting Fragment

Because the nested inside of the fragment life cycle is not controllable!!!

3) Official documentation says at least three methods need to be implemented when creating a fragment:onCreate (), Oncreateview (), OnPause ();

But it seems that just writing a oncreateview is also possible ...

4) The life cycle and activity of the fragment are somewhat similar: three states:

resumed: visible in fragment allowed Paused: Activity visible, but not in focus

stoped:

① Call Addtobackstack () , Fragment was add to Bcak stack

② the activity turns backstage, or the fragment is replaced/deleted


PS: The fragment of the stop State is still alive (all state and member information is maintained by the system), however, it is to the user

No longer visible, and if the activity is killed, he will be killed.


5) Fragment subclasses are:

dialog box:dialogfragment list:listfragment

Option settings:preferencefragment WebView interface :webviewfragment






2) How do I create a fragment?


① static Add fragment


Step 1: define the layout of the fragment, which is what fragment displays

Step 2: Customize a fragment class that requires inheriting fragment or his subclasses, overriding the Oncreateview () method

called in the method: inflater.inflate () method to load the fragment layout file , and then returns the loaded View object

public class Fragmentone extends Fragment {@Overridepublic View oncreateview (layoutinflater inflater, ViewGroup Container,bundle savedinstancestate) {View view = Inflater.inflate (R.layout.fragment1, container,false); return view;}}


The parameters are: the fragment layout to be loaded, the parent viewgroup where the fragment is loaded, and the third parameter is:

Whether to add the parent ViewGroup to the root view of the layout file, but this may result in an extra viewgroup

object; If you don't understand it here, write it false.

In addition the inflate method has other forms, a typical is direct inflate (to show the layout, null),

If you use this: the Layout_xx property of the root view in the item layout is ignored and then set as the default package

Content mode, so it is recommended to use the three-parameter inflate ()! Details of the reasons can be consulted:

Http://www.2cto.com/kf/201407/313054.html



Step 3: Add fragment tags to the layout file for the activity that needs to load fragment .

Remember that the Name property is fully qualified class name Oh, just to include the package name of fragment, such as:

    <fragment        android:id= "@+id/fragment1"        android:name= "Com.jay.example.fragmentdemo.Fragmentone        " Android:layout_width= "Match_parent"        android:layout_height= "0DP"        android:layout_weight= "1"/>
Step 4:activity calls Setcontentview () in the OnCreate () method to load the layout file!





② Adding fragment dynamically


Step 1: call getfragmentmanager to get Fragmentmanager Object FM

Step 2. FM Call BeginTransaction () method Get fragment transaction object BT

Step 3: BT calls add () or relpace () to replace fragment, the parameters are the same

The first parameter is the one you want to pass in containers, The second parameter is Fragment Object

Step 4: Finally, you need to call BT. commit () commit transactions, except add and replace methods

There is also a remove fragment method, also need to commit!

Local code:

Fragment1 f1 = new Fragment1 (); Getfragmentmanager (). BeginTransaction (). Replace (R.ID.LINEARLAYOUT1, F1). commit ();


PS: The code here is the use of fragment under the app package, so the imported fragment-related packages are app Oh!!!

In addition for low version compatibility can also use V4 package, pity Dorado things only, detailed analysis please see:

Fragment with app package or V4 package








3) Fragment interaction with the activity① component gets:

Fragment get the components in activity:

Getactivity (). Findviewbyid (R.id.list)

Activity gets the components in the fragment (either by ID or tag):

Getfragmentmanager.findfragmentbyid (r.id.fragment1);



② Data Transfer


1.Activit Pass data to fragment:

Create bundle packets in activity, call the fragment instance's setarguments (bundle)

The bundle packet is then passed to fragment and then called in fragment getarguments Get

Bundle object, and then parse it.



2.Fragment passing data to activity

in the Fragment in definition a Internal Callback Interface , and then let the fragment containing the the activity implements the callback interface,

Fragment can pass the data through the callback interface, callback, believe that many people know what is the thing, but

Can't write Ah, on-line 100 degree "Fragment data to Activity", all is the code of Li Gang teacher, really no language

Forget it, write down the local code here, I believe the reader can understand the first:


Step 1: define a Callback interface: (in fragment)

/* Interface *      /public interface callback{          /* Defines a method for obtaining information *          /public void GetResult (String result);        

Step 2: interface callback (in fragment)

/* Interface Callback *      /public void GetData (CallBack CallBack) {/          * Gets the text box information, of course you can also pass other types of parameters, see demand slightly * *          String msg = Edittext.gettext (). toString ();          Callback.getresult (msg);      }  

Step 3: read data using the interface callback method (activity)

/* Get data Using interface callback method */  Leftfragment.getdata (New CallBack () {   @Override public         void GetResult (String result) {/              * print information */              Toast.maketext (mainactivity.this, "-->>" + result, 1). Show ();              });  


In summary, it is

Define an interface in fragment, define an abstract method in an interface, what type of data you want to pass

Parameters are set for why type;

And then there's an abstract method in the calling interface that transmits the data to pass through

Then there is the activity, call the method provided by fragment, and then rewrite the abstract method to do the data

can be read!!!



3.Fragment and fragment data transmission


In fact, this is very simple, find the Fragment object to accept the data, directly call the setarguments data into it can be

The usual word is replace, that is, fragment jump when the data transfer, then only need to jump in the initialization of the fragment

Then call his setarguments method to pass in the data!

The approximate code is as follows:

Fragmentmanager Fmanager = Getsupportfragmentmanager (); Fragmenttransaction ftransaction = Fmanager.begintransaction (); Fragmentthree T1 = new Fragmentthree (); Fragmenttwo t2 = new Fragmenttwo (); Bundle bundle = new bundle (); Bundle.putstring ("key", id); t2.setarguments (bundle); Ftransaction.add (R.id.fragmentroot, T2, "~ ~ ~");  Ftransaction.addtobackstack (t1);  Ftransaction.commit ();  


If it is two fragment need to transmit data in real time, rather than jump, you need to get the data from the activity F1, and then pass

to F2.





4) Fragment management and Fragment affairs:① Management:

activity management fragment relies primarily on Fragmentmanager to invoke Findfragmentbyid () gets the specified fragment

You can also call popbackstack () method popup background fragment; You can also call addtobackstack (NULL) Join the Stack

or listen to the background stack changes in: Addonbackstackchangelistener



② Transactions

if it is Replace or delete fragment, you need to use fragmenttransaction object;

also after performing the fragment operation , remember to use it after you have finished the Operation commit () Method Commit a transaction Oh, yes!




5) Finally say a few words:

Believe that the above life cycle diagram 1:30 you will not remember, and finally a little bit about the flow of the first:

①activity load fragment, call the following method in turn:

Onattach, OnCreate, Oncreateview, onactivitycreated, OnStart->onresume;

② when we make a suspended dialog-style activity, or something else, that makes fragment's activity visible, but doesn't get the focus

OnPause

③ when the dialog closes, the activity gets the focus:

Onresume

④ when we replace fragment and call Addtobackstack () to add him to the back stack

OnPause, OnStop, Ondestoryview

Note that the fragment has not been destroyed at this time. Oh!!!

⑤ when we press the back button of the keyboard, fragment will show again:

Oncreateview, onactivitycreated, OnStart, Onresume;

⑥ If we replace it, the Addtobackstack () method is not called before the transaction commit

Fragment is added to the back stack, or if the activity is withdrawn, then fragment will be completely closed,

Fragment will enter the destruction state.

OnPause, OnStop, Ondestoryview, Ondestory, Ondetach





Android Internship notes (4)---Fragment (fragmentation) Basic concept analysis

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.