Android Fragment Basic Knowledge (graphic introduction) _android

Source: Internet
Author: User
Tags commit join static class stub unique id xmlns
Fragment
Android started introducing fragment at the Android 3.0 (API level 11).
You can think of fragment as a module in activity, which has its own layout, has its own lifecycle, handles its own input, and can load or remove fragment modules while the activity is running.
Fragment can be designed as modules that can be reused in multiple activity.
When developing applications that apply to both tablets and phones, you can use fragment to achieve a flexible layout and improve the user experience.
As shown in figure:

the life cycle of fragment
Because the fragment must be embedded in the acitivity, the fragment lifecycle 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, all fragment in the activity cannot be started; If the activity is destroyed, Then all of its fragment will be destroyed.
However, when activity is active, it is possible to control the state of fragment independently, such as adding or removing fragment.
When this is done fragment transaction (conversion), the fragment can be placed in the back stack of the activity so that the user can perform the return operation.

the use of fragment is related
When using fragment, you need to inherit fragment or fragment subclasses (Dialogfragment, Listfragment, Preferencefragment, webviewfragment), So the fragment code looks similar to the activity.
Using the 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 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 allow fragment to be used in systems above the Android 1.6 (API level 4).
To determine that a new version of the APIs is not used on the older version of the system, the following import statement is required:
Copy Code code as follows:

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 project's properties: Right-click the item, select Properties, select 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, some things that still need to be preserved even if they are paused or stopped.
Oncreateview ()
This method is called when the fragment UI is first drawn, and a view must be returned, and null can be returned if fragment does not provide the UI.
Note that if you inherit from Listfragment,oncreateview () The default implementation returns a ListView, so do not implement it yourself.
OnPause ()
When the user leaves fragment, the first call to this method requires some changes to be submitted 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 for fragment are written in the Example_fragment.xml resource file, the Oncreateview () method can be written as follows:
Copy Code code 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; Savedinstancestate provides the data for the previous instance.
three parameters of the inflate () method
The first is the resource ID, which indicates the current fragment corresponding resource file;
The second parameter is the parent container control;
The third Boolean parameter indicates whether the layout and its parent container control are connected, and the situation here is set to False because the system has inserted this layout into the parent control, and setting to True will produce an extra view Group.
add fragment to the activity
When fragment is added to an activity, it is in the corresponding view group.
Fragment has two ways to load: one is to use tags <fragment> declarations in the activity's layout, and another way is to add it to a specified viewgroup in code.
In addition, fragment it may not be any part of the activity layout, it can be an invisible part. This part of the content first skip.
Load Mode 1: Add fragment to activity through the activity's layout file
In the activity's layout file, add the fragment as a child label.
Such as:
Copy Code code 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>

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 invokes their Oncreateview () method to get the corresponding fragment layout and insert the return value into the fragment tag.
There are three ways to provide IDs for fragment
Android:id Property: Unique ID
Android:tag Property: Unique String
If none of the above two are provided, the system uses the container view ID.
Load Mode 2: Add fragment to a viewgroup in a programmatic way
When the activity is in the running state, you can dynamically add fragment to the layout of the active, simply by specifying the parent view group that joins the fragment.
First, you need a fragmenttransaction instance:
Fragmentmanager Fragmentmanager = Getfragmentmanager ()
Fragmenttransaction fragmenttransaction = Fragmentmanager.begintransaction (); (Note, if import Android.support.v4.app.FragmentManager; Then the use is: 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 container for this fragment, the parent control group.
Finally, you need to invoke the commit () method to make the Fragmenttransaction instance change effective.
Instance
Examples of exercises:
Write a class that inherits from the fragment class and writes its layout file (two TextView in this case) and adds the layout to the Oncreateview () method of the Fragment class.
Then add the fragment to the activity in two ways:
The first is the inclusion of <fragment> tags in the activity's layout file;
The second is to join the fragment using the Fragmenttransaction Add () method in the activity code.
Post the Code:
fragment class of your own definition
Copy Code code 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 overloaded generally
@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");
}
}

layout files for fragment
Copy Code code 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 Code code 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 ();
}
}

the layout file for the activity
Copy Code code 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 results of the operation are as follows:
When you see the second way to join the fragment, you specify the ID of the parent container (a linear layout), which already has a button 3, so the fragment is added thereafter.
Reference Resources
Fragment class Documentation:
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.