Use of fragment in Android

Source: Internet
Author: User

Fragment may have been my mind all the time, because Android development is not as systematic as the general process of learning, but rather directly in the company project to change the bug began. It was when fragment was brought up, when he put all his energy into the business logic of combing the code, and missed the fragment First Bus, which is now.

The first two versions of Android release only fit in a small size phone. The development of a small size mobile app just need to consider how to layout the control to the activity, how to open a new activity and so on. However, ANDROID3.0 began to support the tablet and the screen size increased to 10 inches. This has greatly increased the difficulty of Android development because the size of the supported screens has led to the creation of more different sizes of phones, and a simple activity can be difficult to fit into so many different sizes at the same time. In the case of mail applications, we can use one activity to display the message header on a small cell phone, and the other activity to display the message details. But there's a more sensible way to do it on a big screen: the left side of the same activity shows the title, and the details on the right.

Android 3.0 introduces a core class fragment, which elegantly implements the screen-fitting problem in the email example above. At the same time, Android also released an official support library support-v4, using the library to use the fragment interface to adapt to the previous Android version. With this library, we can easily develop applications for mobile phones, tablets and even TVs.

1. What is fragment?

As an example of the email app mentioned above, we want the email app to display a title on a small screen phone, and an activity to show the details. And on the big screen on the left display the title to the right display details.

If we only use activity to fulfill this requirement, we need to create two different activity display processes based on the device type. For mobile phones, you need two activity to collaborate, one containing the ListView activity to display the caption, the other containing the other control combinations to display the details, and for the tablet, you need to recreate an activity that contains the ListView and other controls. When using the scenario above, we can reuse the layout layouts file through tags. But what about the coding section? There is no good way to reuse code. Fragment is to solve this problem of reuse.

The main function of fragment is to combine layouts and their corresponding code together for unified management and reuse. For the Mail app, you can combine the listview portion of the display title into a single fragment that shows the details in a combination of one fragment, so that the activity only needs to display different fragment depending on the situation when it comes to the phone and tablet adaptation. Elegantly solves the problem of code and layout reuse. As shown below:

2, the composition of fragment

Fragment is used to manage the UI, so there must be a view level inside it, and in order to reconstruct the consistency after the fragment is destroyed, you need to pass in a bundle to reconfigure the view.

When fragment is destroyed and rebuilt, Android invokes fragment's null parameter construction method to generate a new object and sets its state by means of an incoming bundle parameter. Therefore, we must preserve its empty construction method when inheriting to fragment.

Because each fragment has its own view, it is possible to replace the original fragment in the activity with a new fragment after an operation, while at the same time wanting to return to the original fragment when the return key is pressed. So fragment again has a design for the return stack.

3. Fragment Life cycle

The life cycle of fragment is much the same as activity, but more complex, with specific processes such as:

Fragment is a class that inherits to object, unlike activity, Android does not create the object for us beforehand, so you must create a fragment object yourself when attaching fragment to an activity.
As mentioned earlier, Android does not create fragment, but when fragment is attached to the activity, Android manages its destruction and rebuilding, which resembles the following code:

 Public Static Myfragment newinstance (int  index) {    new  myfragment ();     New Bundle ();    Args.putint ("index", index);    F.setarguments (args);     return F;}

Therefore, when creating a fragment it is necessary to create an fragment instance in the same way as the above code.

When we attach the created fragment instance to the activity, the callback method of its life cycle begins to work.

Oninflate () callback

Oninflate () executes when fragment is used in the way that labels are added to layout. The main purpose is to provide the attributes in the tag, which can be read from the callback and reserved for later use.

Onattach () callback

When the fragment is attached to the activity immediately after the Onattach (), the callback passes in the attached activity as context.

@Override  Public void Onattach (Context context) {    superOnattach (context);     if instanceof Onfragmentinteractionlistener) {        = (onfragmentinteractionlistener) context;     Else {        thrownew runtimeexception (context.tostring () + "must implement Onfragmentinteractionlistener ");    

The code above uses the Onattach () callback to gracefully implement the listener assignment.

Attention:

1. You can save the context object as a reference to the activity or not, because fragment has a getactivity () that returns the activity you need.

2, after Onattach () can no longer be called setargument (), because Onattach () is attached to the activity, should be determined before the fragment parameters. therefore setargument () should be called as soon as possible.

OnCreate () callback

OnCreate is the next method to execute, when the callback method executes, the entire fragment parameter setting is complete, including the bundle passed in parameters and the Activity object, but does not mean that the view level has been constructed. The callback method is not necessarily after the oncreate of the activity instance. The purpose of the callback exists:

    1. Get incoming bundles;
    2. Provide an early entry for fragment to obtain the required data;

Note: The callback method is all in the main thread, so it is not possible to perform long-time methods such as network requests or reading local large files. You can create threads in OnCreate to get the data, and then return the results by handle or loader.

Oncreateview () callback

Oncreateview () Try the next callback method that you want to execute, which creates a view hierarchy (the View object) and returns it. Parameters include a layoutinflater, a viewgroup, and a bundle. It is important to note that, although there is a parent (viewgroup), we cannot append the created view to the parent. The parent here only provides some references when creating the view, which is then appended automatically.

 Public View Oncreateview (layoutinflater inflater,viewgroup container, Bundle savedinstancestate) {if  Null)returnnullfalse= (TextView) V.findviewbyid ( R.ID.TEXT1); Text1.settext (mydataset[getPosition ()]); return v;}

Note: container is null, stating that there is no fragment on the view level.

Onviewcreated () callback

After Oncreateview and before the UI layout, its parameters are a view, which is the view that was just returned in Oncreateview.

Onactivitycreated () callback

After the onactivitycreated () callback method, fragment can interact with the user. Onactivitycreated () After the activity OnCreate () and all the fragment used in the activity are ready to be completed.

Onviewstaterestored () callback

This callback was introduced after Android 4.2 and was called when fragment was rebuilt, and the rebuild logic must be placed in onactivitycreated () before it can be put here.

OnStart () callback

At this point, fragment is already visible, the callback is consistent with the activity's OnStart (), and the code that previously onstart the callback in the activity can be placed directly here.

Onresume () callback

Consistent with the Onresume () callback of the activity.

OnPause () callback

Consistent with the activity's OnPause ().

Onsaveinstancestate () callback

As with activity, fragment also provides a callback that can hold the state. With this callback method, the state value in the fragment can be saved in the form of bundles and rebuilt at onviewstaterestored (). It is important to note that fragment is being recycled because of memory problems, so you should keep only the data that you need to keep.

If the fragment relies on another fragment, do not attempt to save its immediate reference, but should use the ID or tag.

Note: Although this callback usually occurs after OnPause (), this does not mean that it will be executed immediately after OnPause.

OnStop () callback

Consistent with the activity's OnStop ().

Ondestroyview () callback

The callback before the view view that was created is detached from activity (detach).

OnDestroy () callback

After the view was destroyed, fragment really began to destroy it, and the fragment was already able to find it, but the fragment was unable to do anything.

Ondetach () callback

Detached from activity, fragment does not have a view view level.

Using Setretaininstance ()

Fragment and activity are two separate objects, so there are two options when the activity is destroyed and rebuilt: 1, the fragment;2 is completely rebuilt, the fragment object is preserved on destruction, and is used when the activity is rebuilt, as in the 8-2 dashed path.

Fragment this option to the developer by providing the Setretaininstance () method to decide which approach to use. If the method passes in false, the first is used, otherwise the second method is used.
The time that this method is set can be OnCreate (), Oncreateview (), and Onactivitycreate (), the sooner the better.

Fragment Simple Case

Case code
Case is a similar to the message of the layout of the novel display application, divided into horizontal screen and vertical screen different layout, horizontal screen when the left and right structure, vertical screen display. In order to simplify the implementation process, all data is in-memory data.

The first is the implementation of Main.xml, for the horizontal screen and vertical screen to implement two different main.xml layouts (corresponding to res/layout file directory and Res/layout-land directory respectively)

<?XML version= "1.0" encoding= "Utf-8"?><!--This file is Res/layout/main.xml -<LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"android:orientation= "vertical"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"><Fragmentclass= "Com.androidbook.fragments.bard.TitlesFragment"Android:id= "@+id/titles"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent" /></LinearLayout>
<?XML version= "1.0" encoding= "Utf-8"?><!--This file is Res/layout-land/main.xml -<LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"android:orientation= "Horizontal"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"Android:background= "#fff"><Fragmentclass= "Com.androidbook.fragments.bard.TitlesFragment"Android:id= "@+id/titles"Android:layout_weight= "1"Android:layout_width= "0px"Android:layout_height= "Match_parent"Android:background= "#00550033" /><FramelayoutAndroid:id= "@+id/details"Android:layout_weight= "2"Android:layout_width= "0px"Android:layout_height= "Match_parent" /></LinearLayout>

When the phone is on the vertical screen, the created mainactivity contains only one titlefragment, and when it is a horizontal screen there are two parts, so we implement a method to determine whether it is a multi-panel application.

 Public Boolean Ismultipane () {  return getresources (). GetConfiguration (). Orientation = =  Configuration.orientation_landscape;}

We do this after the load titlesfragment is done: Load an article. For the horizontal screen display to the right for the vertical screen to display to the new activity. So the implementation logic needs to be put to mainactivity,titlesfragment in the appropriate event call mainactivity.

@Override  Public void Onattach (activity myactivity) {    "in titlesfragment Onattach; activity is:" + myactivity);     Super . Onattach (myactivity);     this. myactivity = (mainactivity) myactivity;}
@Override  Public void  onactivitycreated (Bundle icicle) {  super. onactivitycreated (Icicle); ... myactivity.showdetails (mcurcheckposition);}

The realization of ShowDetails

 Public voidShowDetails (intindex) {LOG.V (TAG,"In Mainactivity showDetails (" + Index + ")"); if(Ismultipane ()) {//Check What fragment is shown, replace if needed.Detailsfragment details =(detailsfragment) Getfragmentmanager (). Findfragmentbyid (R.id.details); if(Details = =NULL|| Details.getshownindex ()! =index) {//Make new fragment to show this selection.Details =detailsfragment.newinstance (index); //Execute a transaction, replacing any existing//fragment inside the frame with the new one.LOG.V (TAG, "About to run fragmenttransaction ..."); Fragmenttransaction ft=Getfragmentmanager (). BeginTransaction (); //ft.setcustomanimations (R.animator.fragment_open_enter,//r.animator.fragment_open_exit);        ft.setcustomanimations (R.animator.bounce_in_down, r.animator.slide_out_right); //ft.setcustomanimations (r.animator.fade_in,//r.animator.fade_out); //ft.settransition (fragmenttransaction.transit_fragment_fade);        ft.replace (r.id.details, details);      Ft.addtobackstack (TAG);    Ft.commit (); }}Else{//Otherwise We need to launch a new activity to display//The dialog fragment with selected text.Intent Intent =NewIntent (); Intent.setclass ( This, Detailsactivity.class); Intent.putextra ("Index", index);  StartActivity (Intent); }}

Depending on the screen, display to the right or to the new activity, respectively.
Complete implementation, see Code Https://github.com/votzone/DroidCode/tree/master/Fragments

Note: 1. There are two ways to add and replace fragment in a case

1) Add the Fragmet tag directly via XML and specify its implementation class.

2) dynamically add through Fragmentmanager, just like in detailsfragment, or get the parent view added:

Detailsfragment details = detailsfragment.newinstance (getintent (). Getextras ()); Getfragmentmanager (). BeginTransaction (). Add (Android. R.id.content, details). commit ();
2, when using the fragment reference, you can pass the Fragmentmanager findFragmentByIdOr findFragmentByTagWay to get it. 3. Save the state in the Onsaveinstancestate parameter bundle instance
@Override  Public void   "in Titlesfragment onsaveinstancestate");   Super. Onsaveinstancestate (Icicle); Icicle.putint ("Curchoice", mcurcheckposition);}
4. How to interact with fragment (get references)

1) through FragmentManager findFragmentByTag or findFragmentById to find the fragment, and then call the method

Fragmentother Fragother = (fragmentother) Getfragmentmanager (). Findfragmentbytag ("other"); Fragother.callcustommethod (Arg1, arg2);

2) getTargetFragment() Obtain the reference by locating the targetfragment of the current fragment;

TextView TV = (TextView) gettargetfragment (). GetView (). Findviewbyid (R.ID.TEXT1); Tv.settext ("Set from the Called fragment ");

To set targetfragment for a fragment, you need to use Fragmentmanager, as follows:

New calledfragment (); Mcalledfragment.settargetfragment (this, 0"work"). commit ();

Use of fragment in Android

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.