Android Fragment Basic Introduction

Source: Internet
Author: User
Tags unique id

Fragment

Android was introduced into fragment at Android 3.0 (API level 11).

You can think of fragment as a module in activity, which has its own layout, has its own life cycle, handles its own input individually, and can load or remove fragment modules while the activity is running.

The fragment can be designed as a module that can be reused in multiple activity.

When you develop applications for tablets and phones, you can use fragment to enable flexible layouts and improve the user experience.

  

The life cycle of fragment

Because fragment must be embedded in the acitivity, the life cycle of fragment is closely related to the activity in which it resides.

If the activity is paused, all of the fragment are paused, and if the activity is stopped state, all fragment in the activity cannot be activated, and if the activity is destroyed, Then all of its fragment will be destroyed.

However, when activity is active, you can independently control the state of the fragment, such as adding or removing fragment.

When this is done fragment transaction (conversion), you can put the fragment into the activity's back stack , so that the user can return the operation.

Fragment related to the use of

When using fragment, you need to inherit fragment or fragment subclasses (Dialogfragment, Listfragment, Preferencefragment, webviewfragment), So fragment's code looks similar to the activity.

Using the support Library

The support library is a jar file that provides API library functions so that some new versions of APIs can be used on older versions of Android.

Like Android-support-v4.jar. Its full path is:

<sdk>/extras/android/support/v4/android-support-v4.jar.

It provides fragment APIs that enable the use of fragment on systems above Android 1.6 (API level 4).

In order to determine that no new versions of APIs are being used on older systems, the following import statements are required:

Import android.support.v4.app.Fragment; Import Android.support.v4.app.FragmentManager;

You should also copy the above package into the Libs folder under the Libs project and add it to the properties of the project: Right-click the project, select Properties, choose Java Build Path on the left, and add External JARs ..., Add Android-support-v4.jar.

  When creating an activity that contains fragment, if the support Library is used, then the inheritance should be fragmentactivity rather than activity.

Three callback functions that must be implemented

OnCreate ()

The system calls this method when creating the fragment, where the related components should be initialized, and some things that need to be preserved even if they are paused or stopped.

Oncreateview ()

When the system calls this method the first time the fragment UI is drawn, a view must be returned, and null can be returned if fragment does not provide a UI.

Note that if you inherit from Listfragment,oncreateview () The default implementation returns a ListView, so you don't have to implement it yourself.

OnPause ()

When a user leaves fragment, the first call to this method requires a change to be committed because the user is likely to no longer return.

Implementing the Fragment UI

To provide a fragment UI, you must implement the Oncreateview () method.

Assuming that the layout settings of fragment are written in the Example_fragment.xml resource file, the Oncreateview () method can be written as follows:

  

public static class Examplefragment extends fragment{    @Override public    View Oncreateview (layoutinflater Inflater, ViewGroup container, Bundle savedinstancestate)    {        //inflate the layout for this fragment        return in Flater.inflate (R.layout.example_fragment, container, false);}    }

The container parameter in Oncreateview () represents the fragment parent control in the activity; Savedinstancestate provides the data for the previous instance.

Three parameters of the inflate () method:

The first one is the resource ID, which indicates the current fragment corresponding resource file;

The second parameter is a parent container control;

The third Boolean parameter indicates whether to connect the layout and its parent container control, where the case is set to false, because the system has inserted this layout into the parent control, and setting to True will result in an extra view Group.

Add fragment to the activity

When fragment is added to the activity, it will be in the corresponding view group.

Fragment has two modes of loading: one is to use tags <fragment> declarations in the activity's layout, and the other is to add it to a specified viewgroup in the code.

In addition, fragment it can not be any part of the activity layout, it can be an invisible part. This part of the content is skipped first.

Load Mode 1: Add fragment to activity through the activity's layout file

In the activity's layout file, add fragment as a sub-tag.

Such as:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:orientation=" horizontal "    android:layout_width=" match_parent "    android:layout_ height= "Match_parent" >    <fragment android:name= "com.example.news.ArticleListFragment"            android:id= " @+id/list "            android:layout_weight=" 1 "            android:layout_width=" 0DP "            android:layout_height=" Match_ Parent "/>    <fragment android:name=" com.example.news.ArticleReaderFragment "            android:id=" @+id/viewer "            android:layout_weight=" 2 "            android:layout_width=" 0DP "            android:layout_height=" match_parent "/ ></LinearLayout>

Where the Android:name property fills in the full class name of the fragment you created yourself.

  When the system creates a layout file for this activity, the system instantiates each fragment and calls their Oncreateview () method to get the layout of the corresponding fragment and inserts the return value into the fragment tag's location.

There are three ways to provide ID for fragment:

Android:id Property: Unique ID

Android:tag Property: Unique String

If none of the above two is provided, the system uses the ID of the container view.

Load Mode 2: Programmatically add fragment to a ViewGroup

When the activity is in the running state, you can dynamically join the fragment in the activity layout, just specify the parent view group to join the fragment.

First, you need a fragmenttransaction instance:

Fragmentmanager Fragmentmanager = Getfragmentmanager () fragmenttransaction fragmenttransaction = Fragmentmanager.begintransaction ();

(Note, if import Android.support.v4.app.FragmentManager; then use: Fragmentmanager Fragmentmanager = Getsupportfragmentmanager ();)

  

After that, add the Fragment object with the Add () method:

Examplefragment fragment = new Examplefragment (); Fragmenttransaction.add (R.id.fragment_container, fragment); Fragmenttransaction.commit ();

The first parameter is the fragment container, which is the parent control group.

Finally, the commit () method is called to make changes to the Fragmenttransaction instance take effect.

Instance

Examples of exercises:

Write a class that inherits from the fragment class, and writes its layout file (in this case, two TextView) and joins the layout in the Oncreateview () method of the Fragment class.

This fragment is then added to the activity in two ways:

The first is to add <fragment> tags to the activity's layout file;

The second is to add fragment using the Fragmenttransaction Add () method in the activity's code.

  Post the Code:

Self-defined fragment class:

Examplefragment.java

Fragment layout file:

Example_fragment_layout.xml

Main activity:

Learnfragment.java

Activity's layout file:

Activity_learn_fragment.xml

The results of the operation are as follows:

When you see the second way to join fragment, you specify the ID of the parent container (a linear layout), which already has a button 3, so fragment is added thereafter.

Reference Resources

Fragment class Documents:

Http://developer.android.com/reference/android/app/Fragment.html

Training:building a Dynamic UI with fragments

Http://developer.android.com/training/basics/fragments/index.html

Fragments Develop Guide:

Http://developer.android.com/guide/components/fragments.html

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.