Basic knowledge about Android Fragment (Graphic Introduction)

Source: Internet
Author: User

Fragment
Android introduced Fragment in Android 3.0 (API level 11.
You can think of Fragment as a module in the Activity. This module has its own layout, lifecycle, and processing of its own input. The Fragment module can be loaded or removed when the Activity is running.
Fragment can be designed as a module that can be reused in multiple activities.
Fragment can be used to achieve flexible layout and improve the user experience when developing applications for both tablet and mobile phones.


Fragment Lifecycle
Because Fragment must be embedded in Acitivity, the lifecycle of Fragment is closely related to its Activity.
If the Activity is paused, all Fragment is paused. if the Activity is stopped, all Fragment in the Activity cannot be started. If the Activity is destroyed, all Fragment in it will be destroyed.
However, when the Activity is active, you can independently control the Fragment status, such as adding or removing Fragment.
When performing the fragment transaction (conversion), you can put the fragment in the back stack of the Activity so that the user can perform the return operation.

Fragment usage
When using Fragment, You need to inherit the Fragment or Fragment subclass (DialogFragment, ListFragment, PreferenceFragment, WebViewFragment), so the Fragment code looks similar to the Activity.
Use Support Library
The Support Library is a JAR file that provides API Library functions, so that you can use some new versions of APIs on the old Android version.
For example, android-support-v4.jar. Its complete path is:
<Sdk>/extras/android/support/v4/android-support-v4.jar.
It provides the Fragment APIs so that Fragment can be used in Android 1.6 (API level 4) and later systems.
To ensure that the new version of APIs is not used on the old version of the system, the following import statement is required: Copy codeThe Code is as follows: import android. support. v4.app. Fragment;
Import android. support. v4.app. FragmentManager;

At the same time, you should merge the above package into the libs folder under the libs project, and then add in the project Properties: Right-click the project, select Properties, and select Java Build Path on the left, then Add External JARs ..., Add android-support-v4.jar.

When creating an Activity that contains Fragment, if the Support Library is used, the inherited Activity should be FragmentActivity rather than Activity.
Three required callback Functions
OnCreate ()
The system calls this method when creating Fragment. The related components should be initialized here, and some items should be retained even when they are paused or stopped.
OnCreateView ()
When the system calls this method when drawing the Fragment UI for the first time, a View must be returned. If Fragment does not provide the UI, null can be returned.
NOTE: If it is inherited from ListFragment, the default Implementation of onCreateView () will return a ListView, so you do not need to implement it yourself.
OnPause ()
When the user leaves Fragment, the first call of this method requires some changes, because the user may not return any more.
Implement the Fragment UI
Provides the Fragment UI. The onCreateView () method must be implemented.
If the layout settings of Fragment are written in the example_fragment.xml resource file, the onCreateView () method can be written as follows:Copy codeThe Code is 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 inflater. inflate (R. layout. example_fragment, container, false );
}
}

The container parameter in onCreateView () represents the parent control of the Fragment in the Activity. The savedInstanceState provides the data of the previous instance.
Three parameters of the inflate () method:
The first is the resource ID, indicating the resource file corresponding to the current Fragment;
The second parameter is the parent container control;
The third Boolean parameter indicates whether to connect the layout and its parent container control. In this case, it is set to false because the layout has been inserted to the parent control, if this parameter is set to true, an additional View Group is generated.
Add Fragment to Activity
When Fragment is added to the Activity, it is in the corresponding View Group.
Fragment has two loading methods: one is to use the label <fragment> declaration in layout of the Activity, and the other is to add it to a specified ViewGroup in the code.
In addition, Fragment can not be any part of the Activity layout. It can be an invisible part. This part is skipped first.
Loading Method 1: Add Fragment to Activity through the layout file of Activity
In the Activity layout file, add Fragment as a sub-tag.
For example:Copy codeThe Code is as follows: <? 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>

The android: name attribute fills in the complete Class name of the fragment you have created.
When the system creates a layout file for this Activity, the system will instantiate each fragment and call their onCreateView () method to obtain the layout of the corresponding fragment, insert the returned value to the location where the fragment tag is located.
There are three methods to provide ID for Fragment:
Android: id property: Unique id
Android: tag attribute: unique string
If neither of the above is provided, the system uses the container view ID.
Loading Method 2: Add Fragment to a ViewGroup by programming
When the Activity is in the Running state, you can dynamically add Fragment to the layout of the Activity. You only need to specify the parent View Group to add the Fragment.
First, you need a FragmentTransaction instance:
FragmentManager fragmentManager = getFragmentManager ()
FragmentTransaction fragmentTransaction = fragmentManager. beginTransaction (); (Note: If you import android. support. v4.app. FragmentManager; FragmentManager = getsuppfrfragmentmanager ();)

Then, use the add () method to add the Fragment object:
ExampleFragment fragment = new ExampleFragment ();
FragmentTransaction. add (R. id. fragment_container, fragment );
FragmentTransaction. commit ();
The first parameter is the container of the fragment, that is, the parent control group.
Finally, you need to call the commit () method to make the change of the FragmentTransaction instance take effect.
Instance
Example:
Write a class that inherits from the Fragment class and write the layout file (two textviews in this example). Add the layout to the onCreateView () method of the Fragment class.
Then add the fragment to the Activity in two ways:
First, add the <fragment> label to the Activity layout file;
The second is to use the add () method of FragmentTransaction in the Activity code to add fragment.
Paste the Code:
Custom fragment class:Copy codeThe Code is as follows: ExampleFragment. java
Package com. example. learningfragment;
Import android. OS. Bundle;
Import android. support. v4.app. Fragment;
Import android. view. LayoutInflater;
Import android. view. View;
Import android. view. ViewGroup;
Public class ExampleFragment extends Fragment
{
// Three methods that must be reloaded
@ Override
Public void onCreate (Bundle savedInstanceState)
{
// TODO Auto-generated method stub
Super. onCreate (savedInstanceState );
System. out. println ("ExampleFragment -- onCreate ");
}
@ Override
Public View onCreateView (LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
System. out. println ("ExampleFragment -- onCreateView ");
Return inflater. inflate (R. layout. example_fragment_layout, container, false );
}
@ Override
Public void onPause ()
{
// TODO Auto-generated method stub
Super. onPause ();
System. out. println ("ExampleFragment -- onPause ");
}
@ Override
Public void onResume ()
{
// TODO Auto-generated method stub
Super. onResume ();
System. out. println ("ExampleFragment -- onResume ");
}
@ Override
Public void onStop ()
{
// TODO Auto-generated method stub
Super. onStop ();
System. out. println ("ExampleFragment -- onStop ");
}
}

Fragment layout File:Copy codeThe Code is as follows: example_fragment_layout.xml
<? Xml version = "1.0" encoding = "UTF-8"?>
<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"
Android: layout_width = "match_parent"
Android: layout_height = "match_parent"
Android: orientation = "vertical">
<TextView
Android: layout_width = "match_parent"
Android: layout_height = "wrap_content"
Android: text = "@ string/num1"
/>
<TextView
Android: layout_width = "match_parent"
Android: layout_height = "wrap_content"
Android: text = "@ string/num2"
/>
</LinearLayout>

Main Activity:Copy codeThe Code is as follows: LearnFragment. java
Package com. example. learningfragment;
Import android. OS. Bundle;
Import android. support. v4.app. FragmentActivity;
Import android. support. v4.app. FragmentManager;
Import android. support. v4.app. FragmentTransaction;
Public class LearnFragment extends FragmentActivity
{
@ Override
Public void onCreate (Bundle savedInstanceState)
{
Super. onCreate (savedInstanceState );
SetContentView (R. layout. activity_learn_fragment );
// Add Fragment to the program
FragmentManager fragmentManager = getSupportFragmentManager ();
FragmentTransaction fragmentTransaction = fragmentManager. beginTransaction ();
ExampleFragment fragment = new ExampleFragment ();
FragmentTransaction. add (R. id. linear, fragment );
FragmentTransaction. commit ();
}
}

Activity layout File:Copy codeThe Code is as follows: activity_learn_fragment.xml
<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"
Xmlns: tools = "http://schemas.android.com/tools"
Android: layout_width = "match_parent"
Android: layout_height = "match_parent"
Android: orientation = "vertical"
>
<Button
Android: id = "@ + id/btn1"
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content"
Android: text = "@ string/btn1"
/>
<Fragment
Android: name = "com. example. learningfragment. ExampleFragment"
Android: id = "@ + id/fragment1"
Android: layout_width = "match_parent"
Android: layout_height = "wrap_content"
/>
<Button
Android: id = "@ + id/btn2"
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content"
Android: text = "@ string/btn2"
/>
<LinearLayout
Xmlns: android = "http://schemas.android.com/apk/res/android"
Android: id = "@ + id/linear"
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content"
Android: orientation = "vertical"
>
<Button
Android: id = "@ + id/btn3"
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content"
Android: text = "@ string/btn3"
/>
</LinearLayout>
</LinearLayout>

The running result is as follows:
We can see that when the second method is added to fragment, the id of the parent container (a linear layout) is specified, where there is already a Button 3, so fragment is added after it.
Reference resources
Fragment 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

Related Article

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.