Android UI Programming (7)--fragment

Source: Internet
Author: User
Tags unique id

A fragment is a part or a behavior in the interface of an activity. You can combine multiple fragment into one activity to create a faceted interface and to reuse a fragment in multiple activity. You can also think of fragment as a modular activity that has its own life cycle, receives its own events, and can be added or deleted while the activity is running.

Fragment cannot exist independently, it must be embedded in the activity, and the life cycle of fragment is directly affected by the activity in which it resides. For example, when activity is paused, all the fragment that it owns are paused, and when the activity is destroyed, all of its fragment are destroyed. However, when the activity is running (before Onresum (), OnPause (), you can manipulate each fragment individually, such as adding or removing them. When performing the above transactions for fragment, you can add transactions to a stack that is managed by the activity and each of the stacks is a fragment transaction. With this stack, you can reverse-execute the fragment transaction so that the "back" key (navigating backwards) can be supported at the fragment level.

When a fragment is added to the activity, it is placed in the ViewGroup control and needs to be defined fragment its own interface. You can declare fragment in the layout XML file, the element is:<fragment>;, you can create fragment in your code, and then add it to the ViewGroup control. However, fragment does not have to be placed in the activity interface, it can be hidden in the background for the activity work.

fragment key points :

1, fragment as part of the activity interface appears

2. Multiple fragment can occur simultaneously in one activity, and a fragment can also be used in multiple activity

3, during the activity operation, you can add, remove or replace fragment (add (), remove (), replace ())

Design Philosophy :

Android introduced fragment from 3.0, primarily to support more dynamic and flexible interface designs, such as those used on tablets. The platform has a larger screen space than the phone to assemble and interact with the interface components. Fragment makes it unnecessary to deal with complex changes in the view tree when doing such a design. By dividing the layout of activity into fragment, you can change the way it looks when the activity is running, and you can save the change in the activity's fallback stack.

For example: Write a read the news program, you can display the title list with one fragment, the other fragment display the contents of the selected title, the two fragment are on an activity, side-by-side display. Then these two fragment have their own life cycles and respond to events of interest to them. So, there's no need to display a list of headlines like the one on the phone, and the other activity to show the news content; You can now display both on an activity. Such as:


Fragment must be written into reusable modules. Because fragment has its own layout, its own event, its own life cycle and behavior, all can include a different instance of a fragment in multiple activities. This is especially important for your interface to be able to experience the user's perfect performance in different screen sizes. For example, you can start an activity that contains a lot of fragment while the program is running on a large screen, and start an activity that contains a small amount of fragment when running on a small screen.

For example: or the program that read the news just now, when the program runs on the big screen, start activity A, the title list and the news content of this two fragment are placed in activity a, and when the program runs on a small screen, or start activity A, But at this point in a, only the title list fragment, when a title is selected, activity a launches activity B,b contains news content fragment.

Create fragment:

To create a fragment, you must send a new class from a derived class of fragment or fragment. Fragment's code is somewhat like activity. It has the same callback methods as the activity, such as OnCreate (), OnStart (), OnPause (), and OnStop (). In fact, if you want to change the old program to use fragment, basically just move the code of the activity's callback method to the corresponding callback method in fragment.

It is often necessary to implement the following life cycle functions :

onCreate ()-this method is called by the system when the fragment is created. In which you must initialize the fragment's basic components, refer to the activity's instructions

Oncreateview ()-this method is called when the system fragment to draw its own interface (before it is being displayed). This method must return the root control of the fragment layout. If this fragment does not provide an interface, you can return null. That is, the system calls this method the first time fragment draws its user interface. In order to draw the fragment UI, this method must return a view, which is the root view of the fragment layout. If fragment does not provide a UI, you can return null.

OnPause ()--When the user is about to leave fragment, the system calls this method as the first indication (however it does not always mean that the fragment will be destroyed). Before the end of the user painting of the current polygon, it is common to submit any changes that should persist here (because the user may not return).

the life cycle of fragment :


In addition to inheriting base class fragment, there are some subclasses that can inherit

Dialogfragment

Displaying a floating dialog box, using this class to create a dialog is a good alternative to using the dialog tool method of the activity class, because you can merge a fragment dialog box into the activity-managed fragment back stack (fallback stack). Allows the user to return a fragment that was previously discarded.

Listfragment

Displays a list of items that are managed by adapter (for example, Simplecursoradapter), similar to listactivity. It provides methods to manage a list View, such as a Onlistitemclick () callback to handle a click event.

Preferencefragment

Displays a list of hierarchies for a preference object, similar to preferenceactivity. This is useful when creating a "set up" activity for your app

Example One :

androidmanifest.xml--did not make any changes to create the project by default

<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "/http  Schemas.android.com/apk/res/android "package=" Com.wxl.fragment "android:versioncode=" 1 "android:versionname=" 1.0 "        > <USES-SDK android:minsdkversion= "8" android:targetsdkversion= "/> <application" Android:allowbackup= "true" android:icon= "@drawable/ic_launcher" android:label= "@string/app_name" an            Droid:theme= "@style/apptheme" > <activity android:name= "com.wxl.fragment.MainActivity" Android:label= "@string/app_name" > <intent-filter> <action android:name= "Android.int Ent.action.MAIN "/> <category android:name=" Android.intent.category.LAUNCHER "/> </i Ntent-filter> </activity> </application></manifest> 
Fragment1.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: Background= "#ffcccc"    android:orientation= "vertical" >        <textview         android:id= "@+id/fragment1_ TextView "        android:layout_width=" match_parent "        android:layout_height=" Match_parent "        android: gravity= "center"        android:text= "First Fragment Interface"/></linearlayout>
Fragment2.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: Background= "#fffccc"    android:orientation= "vertical" >    <textview         android:id= "@+id/fragment2_ TextView "        android:layout_width=" match_parent "        android:layout_height=" match_parent "        android:gravity = "Center"        android:text= "second fragment interface"/>    </LinearLayout>

Activity_main.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= "Horizontal"    tools:context= ". Mainactivity ">    <fragment         android:id=" @+id/fragment1 "        android:layout_width=" 0dip "        Android : layout_height= "match_parent"        android:name= "com.wxl.fragment.Fragment1"        android:layout_weight= "1"/ >    <fragment         android:id= "@+id/fragment2"        android:layout_width= "0dip"        android:layout_ height= "Match_parent"        android:name= "Com.wxl.fragment.Fragment2"        android:layout_weight= "1"/></ Linearlayout>

Fragment1.java

Package Com.wxl.fragment;import Android.os.bundle;import Android.support.v4.app.fragment;import Android.view.layoutinflater;import Android.view.view;import Android.view.viewgroup;public class Fragment1 extends Fragment {@Overridepublic View oncreateview (layoutinflater inflater, ViewGroup container,bundle savedinstancestate) {/ /TODO auto-generated method Stubreturn inflater.inflate (R.layout.fragment1, Container,false);}}
Fragment2.java

Package Com.wxl.fragment;import Android.os.bundle;import Android.support.v4.app.fragment;import Android.view.layoutinflater;import Android.view.view;import Android.view.viewgroup;public class Fragment2 extends Fragment {@Overridepublic View oncreateview (layoutinflater inflater, ViewGroup container,bundle savedinstancestate) {/ /TODO auto-generated method Stubreturn inflater.inflate (R.layout.fragment2, Container,false);}}
Mainactivity.java

Package Com.wxl.fragment;import Android.os.bundle;import Android.support.v4.app.fragmentactivity;public class Mainactivity extends Fragmentactivity {    @Override    protected void onCreate (Bundle savedinstancestate) {        Super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);    }}
Note

When using fragment statically in activity, be aware of two places:

Fragment refers to the package is:import android.support.v4.app.Fragment; rather than import android.app.Fragment;

then the activity must be inherited fragmentactivity, the reference package is: Import android.support.v4.app.FragmentActivity;


Logcat Printing Information : (fragmentactivity)


To add a user interface :

Fragment is often used as part of an activity's user interface and provides its layout to the activity. In order to provide a layout for a fragment, the Oncreateview () callback method must be implemented, and when the fragment draws its own layout, the Android system calls it. The implementation code for this method must return a root view of the fragment layout.

public class Fragment1 extends Fragment {@Overridepublic View oncreateview (layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {//TODO auto-generated method Stubreturn inflater.inflate (R.layout.fragment1, container, false);}}
The container parameter for incoming Oncreateview () is the parent viewgroup (from the activity's layout) that fragment layout will be inserted into. The Savedinstancestate parameter is a bundle that, if fragment is restored, provides information about the previous instance of fragment.

Inflater.inflate (R.layout.fragment1, Container,false);

    • Parameter one: The resource ID of the layout you want to load
    • Parameter two: The parent viewgroup of the loaded layout. It is important to pass in the container to allow the system to accept the layout parameter of the root view of the layout to be loaded, by which it assigns the parent view to be anchored
    • Parameter three: A Boolean value indicates whether the expanded layout should be attached to ViewGroup (the second parameter) during loading. (In this example, FALSE is specified because the system has inserted the expanded layout into container, and passing in true creates an extra viewgroup in the final layout).
add fragment to activityTypically, fragment provides a part of the UI for the host activity and is embedded as an entire part of the activity. There are two ways to add a fragment to activity layout.

Method One: Declare fragment in the activity's layout file

In this case, you can specify the layout property for fragment as you would for a view:

<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= "Horizontal"    tools:context= ". Mainactivity ">    <fragment         android:id=" @+id/fragment1 "        android:layout_width=" 0dip "        Android : layout_height= "match_parent"        android:name= "com.wxl.fragment.Fragment1"        android:layout_weight= "1"/ >    <fragment         android:id= "@+id/fragment2"        android:layout_width= "0dip"        android:layout_ height= "Match_parent"        android:name= "Com.wxl.fragment.Fragment2"        android:layout_weight= "1"/></ Linearlayout>
The Android:name property in <fragment> specifies the fragment class that is instantiated in layout.

When the system creates this activity layout, it instantiates each fragment specified in the layout and invokes each of the Oncreateview () methods on it to get the layout of each fragment. The system will be inserted directly from the returned view to where the <fragment> element is located.

Note : Each fragment requires a unique identity, and if the activity restarts, the system can be used to recover the fragment (and can also be used to capture fragment to process transactions, such as removing it)

There are 3 ways to provide an identity for a fragment:

    • Provide a unique ID for the Android:id property
    • Provides a unique string for the Android:tag property
    • If none of the above 2 are provided, the system uses the ID of the container view
method Two: Write code to add fragment to an existing ViewGroupFragment can be added to activity layout at any time when the activity is running. Simply specify a viewgroup that needs to be placed fragment in order to manipulate fragment transactions (such as adding, removing, or replacing a fragment) in the activity. You must use an API from Fragmenttransaction to get an instance of Fragmenttransaction from activity as follows
Fragmentmanager Fragmentmanager = Getfragmentmanager (); Fragmenttransaction fragmenttransaction = Fragmentmanager.begintransaction ();
You can then add a fragment using the Add () method, specifying the fragment to add and the view to insert
Fragment1 fragment = new Fragment1 ();  Fragmenttransaction.add (r.id.main,fragment);  Fragmenttransaction.commit ();
Add () The first parameter is the viewgroup that fragment to be placed, specified by the resource ID. The second parameter is the fragment that needs to be added. Once a change has been made with fragmenttransaction, a commit must be called in order for the change to take effect。 Where Fragment1 is the new class that you continue to fragment the base class or derived class.

Fragmentmanager:

Fragmentmanager is able to manage the fragment in the activity by invoking the activity's Getsupportfragmentmanager () to get its instance.

Some things fragmentmanager can do :

1. Use Findfragmentbyid () (fragment for providing a UI in activity layout) or Findfragmentbytag () (for fragment with or without UI) Get the fragment that exist in the activity

2. Pop the fragment from the background stack and use Popbackstack () (Impersonate the user to press the back command)

3. Use Addonbackstackchangelistenner () to register a listenner that listens for background stack changes

fragmenttransaction:

Fragmenttransaction adds, removes, replaces, and performs other actions on fragment. Get an example of a fragmenttransaction from Fragmentmanager:

Fragmentmanager Fragmentmanager = Getfragmentmanager (); Fragmenttransaction fragmenttransaction = Fragmentmanager.begintransaction ();
Each transaction is a set of changes to be executed at the same time, you can set all the changes you want to perform in a given transaction, use such as add (), remove (), replace (), and then apply the transaction to the activity, you must call commit ().

example two--according to the above example, the above Activity_main.xml, Fragment1.java, and Mainactivity.java have been partially modified as followsFragment1.javaThe original guide package import android.support.v4.app.Fragment; the import android.app.Fragment; Activity_main.xml
<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:id=" @+id/main "android:layout_width=" match_parent "android:layout_height=" MATC H_parent "android:orientation=" Horizontal "tools:context=".         Mainactivity "> <linearlayout android:id=" @+id/main_linearlayout1 "android:layout_width=" 0dip "            android:layout_height= "Match_parent" android:layout_weight= "1" android:orientation= "vertical" > </LinearLayout> <linearlayout android:id= "@+id/main_linearlayout2" Android:layout_ Width= "0dip" android:layout_height= "Match_parent" android:layout_weight= "1" android:orientation= "vert        ical "> <fragment android:id=" @+id/fragment2 "android:layout_width=" Match_parent "    android:layout_height= "Match_parent" android:name= "Com.wxl.fragment.Fragment2"/>        </LinearLayout></LinearLayout> 
Mainactivity.java
Package Com.wxl.fragment;import Android.annotation.suppresslint;import Android.app.fragmentmanager;import Android.app.fragmenttransaction;import Android.os.bundle;import Android.support.v4.app.fragmentactivity;public Class Mainactivity extends fragmentactivity{    @SuppressLint ("Newapi") @Override    protected void OnCreate ( Bundle savedinstancestate) {        super.oncreate (savedinstancestate);        Setcontentview (r.layout.activity_main);               Fragmentmanager Fragmentmanager = Getfragmentmanager ();       Fragmenttransaction fragmenttransaction = Fragmentmanager.begintransaction ();              Fragment1 fragment1 = new Fragment1 ();       Fragmenttransaction.add (R.ID.MAIN_LINEARLAYOUT1, fragment1);       Fragmenttransaction.commit ();                  }}
Note: This example fragment2 is added directly in Activity_main.xml, and Fragment1 is added using code in Mainactivity.java.Using XML, that is, the use of one add Fragment when the use of android.support.v4.app.Fragment; all import packages in Fragment2.java are: Import android.support.v4.app.Fragment;Using the code mode, that is, the use of two add Fragment when the use of android.app.Fragment; all import packages in Fragment1.java are: import android.app.Fragment;in this case, there are two ways in which all activity in Mainactivity.java needs to inherit fragmentactivity (which is needed) without inheriting fragmentactivity. and pay attention.
Inflater.inflate (R.layout.fragment1, Container,false);
The third argument must be false and cannot be true, otherwise the following prompt error Mainactivity.java activity needs to inherit fragmentactivity (mode one needs to be used), otherwise the following prompt error is present

Android UI Programming (7)--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.