[Android] (Study note 1) The basic method of using activity to host fragment

Source: Internet
Author: User

The activity managed fragment needs to do the following two points:

1. Arrange the position for the fragment view in the layout;

2. Manage the life cycle of fragment instances.

The life cycle of fragment:

Reference:http://www.cnblogs.com/purediy/p/3276545.html

Fragment represents activity, and its life cycle state reflects the activity's life cycle state. The key difference between the fragment life cycle and the activity life cycle is that thefragment lifecycle approach is called by managed activity rather than by the operating system. fragment the use of the activity of their own internal things.

Activity as a container hosting internal fragment, using code to flexibly add fragment is a good choice. The following general steps are given:

1. define the activity1 layout file (file name Activity1.xml), which is used primarily to schedule locations for the fragment1 to be added

Activity1.xml:
1 <?XML version= "1.0" encoding= "Utf-8"?>2 <Framelayoutxmlns:android= "Http://schemas.android.com/apk/res/android"3 Android:id= "@+id/fragmentcontainer"4 Android:layout_width= "Match_parent"5 Android:layout_height= "Match_parent"6 />

3rd Act The framelayout adds an ID number to facilitate subsequent use. This framelayout is where the fragment1 appears. Note that this layout file is not limited to an object of a fragment class, it only describes the basic information of a container.

2. Create UI Fragment

The steps to create a UI fragment are the same as for creating an activity:

    • Define layout file, assemble interface;
    • Create a Fragment1 class and set its view layout to the part defined in the previous step;
    • Connect the generated components in the layout file in a way that uses code.

Here is a detailed description of the details of each step.

(1) Define the layout of the Fragment1 (fragment1.xml):

1 <?XML version= "1.0" encoding= "Utf-8"?>2 <LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"3 Android:layout_width= "Match_parent"4 Android:layout_height= "Match_parent"5 android:orientation= "vertical" >6     7     <TextView8         Android:layout_width= "Match_parent"9 Android:layout_height= "Wrap_content"Ten Android:text= "@string/crime_title_label" One style= "? Android:listseparatortextviewstyle"/> A     <EditText -         Android:id= "@+id/crime_title" - Android:layout_width= "Match_parent" the Android:layout_height= "Wrap_content" - Android:layout_marginleft= "16DP" - Android:layout_marginright= "16DP" - Android:hint= "@string/crime_title_hint" +         /> -     <TextView +         Android:layout_width= "Match_parent" A Android:layout_height= "Wrap_content" at Android:text= "@string/crime_details_label" - style= "? Android:listseparatortextviewstyle"/> -     <Button -         Android:id= "@+id/crime_date" - Android:layout_width= "Match_parent" - Android:layout_height= "Wrap_content" in Android:layout_marginleft= "16DP" - Android:layout_marginright= "16DP" to         /> +     <CheckBox -         Android:id= "@+id/crime_solved" the Android:layout_width= "Match_parent" * Android:layout_height= "Wrap_content" $ Android:layout_marginleft= "16DP"Panax Notoginseng Android:layout_marginright= "16DP" - Android:text= "@string/crime_solved_label" the         /> + </LinearLayout>
View Code

The string resource contained in the code is considered to have been added to Res/values/strings.xml by default

(2) Create the Fragment1 class and use the layout defined by the Fragment1.xml:

1  Public class extends Fragment {2@Override3  publicvoid  onCreate (Bundle Savedinstancestate) {4Super. OnCreate (savedinstancestate); 5 }6 }           

Note that in the class definition of fragment1, there is no view in the OnCreate method that generates FRAGMENT1. We will complete the creation and configuration of the Fragment1 view in another fragment life cycle approach:

Public View Oncreateview (Layoutinflater inflater, ViewGroup parent,bundle savedinstancestate)

Using this method, the Fragment1 view object created by Layoutinflater is returned to the managed activity1.

The code that defines the class Fragment1 is updated to:

1  Public classFragment1extendsFragment {2     @Override3      Public voidonCreate (Bundle savedinstancestate) {4       Super. OnCreate (savedinstancestate);5     }6 7     @Override8      PublicView Oncreateview (layoutinflater inflater, ViewGroup parent,bundle savedinstancestate) {9View v = inflater.inflate (r.layout.fragment1, parent,false);Ten     } One}

The Oncreateview method is called after the OnCreate call, as described in the life cycle of the fragment. Note the 9th line of code, called the Fragment1 view generated by the Layoutinflater.inflate method, is passed to the FRAGMENT1 layout resource ID. In order to add a fragment1 view to the parent view by code, the third parameter here is false.

(3) Connect the generated components in the layout file in a way that uses code:

The created View Object v also defines a series of controls (see Fragment1.xml definition), which can be obtained by View.findviewbyid.

3. add fragment to activity

Adding fragment1 to managed activity1 requires the use of Fragmentmanager, which is responsible for managing the fallback stack for fragment queues and fragment transactions.

To get the fragment manager for managed activity1, you can add a call to the Getfragmentmanager method in its OnCreate method:

1  Public classActivity1extendsfragmentactivity {2     @Override3      Public voidonCreate (Bundle savedinstancestate) {4       Super. OnCreate (savedinstancestate);5       Setcontentview (r.layout.activity1);6 7Fragmentmanager FM =Getfragmentmanager ();//<--NEW CODE8     }  9}

Adding a Fragment1 instance to activity1 is actually committing a new fragment transaction (add transaction) to the Fragmentmanager, first look at the code:

 Public classActivity1extendsfragmentactivity {protected AbstractFragment createfragment (); @Overrideprotected voidonCreate (Bundle savedinstancestate) {//Step1        Super. OnCreate (savedinstancestate);                Setcontentview (r.layout.activity1); Fragmentmanager FM=Getfragmentmanager (); //using Container view resource to apply a fragment from Fragmentmanager. <resource ID <--> fragment>        /** Fragmentmanager manages a fragment queue, and the container view resource can be bound to a specific fragment. * The program tries to find the fragment that is bound to the resource ID (r.id.fragmentcontainer) in the current Fragmentmanager managed fragment queue, and returns the fragment if found, or submits a Add a new fragment to the queued transaction, bind the new fragment and specify the * resource (R.id.fragmentcontainer) before committing.         The actual function of this code is to ensure that the fragment bound with R.id.fragmentcontainer exists in the fragment queue of the current Fragmentmanager management.         * After adding fragment transaction commits, the fragment's Lifecycle method OnCreate method and Oncreateview method are called sequentially, * Fragmentmanager is responsible for invoking the fragment life-cycle method in the queue. */Fragment Fragment=Fm.findfragmentbyid (R.id.fragmentcontainer); if(Fragment = =NULL) {Fragment=createfragment (); //Step2fm.begintransaction (). Add (R.id.fragmentcontainer, Fragment). commit (); }    }}

More detailed comments have been added to the code. The general meaning is to use the resource ID (r.id.fragmentcontainer) to find the corresponding fragment (to find an instance of fragment1), if there is no match in the current fragment queue, submit an Add transaction, add one with the resource ID (r.id.frag Mentcontainer) corresponds to the fragment (a new instance of Fragment1). This resource ID is the ID of the fragment1 corresponding container (that is, framelayout) mentioned at the beginning.

To summarize:

Activity1 layout corresponds to R.layout.activity1

The instance object of Fragment1 corresponds to R.id.fragmentcontainer, also from the side, fragment1 instance is just a component of managed Activity1

The layout of view V in fragment1 corresponds to R.layout.fragment1

In addition, there may already be instances of fragment1 in the fragment queue managed by Fragmentmanager (otherwise why not find one by ID number first), Why? Imagine that if Activity1 is destroyed because of device rotation or memory recycling, the entire fragment queue that originally existed in activity1 will be saved, naturally including instances of fragment1. Activity1 will call the OnCreate method when rebuilding, the new Fragmentmanager first obtains the previously saved fragment queue, the convenient reply previous state, the fragment1 old instance has already existed naturally.

After three steps, the Fragment1 instance was successfully managed by activity1 (that is, successfully added to Activity1).

Next: The main summary of the interface layout-related knowledge.

[Android] (Study note 1) The basic method of using activity to host fragment

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.