"Android" 11.5 Create and manage fragments

Source: Internet
Author: User

Category: C #, Android, VS2015;

Date Created: 2016-02-22 I. INTRODUCTION

To manage the fragment in your activity, you can use the Fragmentmanager class to implement it. An instance of the class is obtained by calling Getfragmentmanager () in the activity.

The things you can do with Fragmentmanager are:

L Use Findfragmentbyid () (used to provide interface fragment in the activity layout) or Findfragmentbytag () Gets the fragment that exist in the activity (for fragment with or without an interface).

L Eject fragment from the background stack using Popbackstack () (imitating the user's back command).

L use Addonbackstackchangedlistener () to register a listener that listens for changes in the background stack.

For more information about these functions and more, refer to the documentation for the Fragmentmanager class. Ii. Creation of Fragment

1. Add Example_fragment.axml File

Typically, fragment constructs a partial interface to its host activity, which is embedded as part of the activity's full view hierarchy.

The following is a layout file containing two fragment:

<?XML version= "1.0" encoding= "Utf-8"?>    <LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"android:orientation= "Horizontal"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent">        <FragmentAndroid:name= "Com.example.news.ArticleListFragment"Android:id= "@+id/list"Android:layout_weight= "1"Android:layout_width= "0DP"Android:layout_height= "Match_parent" />        <FragmentAndroid: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 property in <fragment> specifies the fragment class that is instantiated in the layout.

Note: Java does not allow the use of uppercase package names (Java's "packages" are called "namespaces" in C #), but there is no such restriction in C #. For example, the following two ways are legal:

<fragment android:name= "Com.example.DetailsFragment"

Android:id= "@+id/fragment_content"

Android:layout_width= "Match_parent"

android:layout_height= "Match_parent"/>

You can also write this:

<fragment android:name= "Com.Example.DetailsFragment"

Android:id= "@+id/fragment_content"

Android:layout_width= "Match_parent"

android:layout_height= "Match_parent"/>

When the system creates an activity layout, it instantiates each of the fragment specified in the layout file and calls the Oncreateview () function for them to get the layout of each fragment. The system inserts the view returned by the fragment directly at the location of the <fragment> element.

Note: Each fragment requires a unique identifier (ID), which is used to recover the fragment (and to capture fragment transactions, such as removal) if the activity is restarted.

There are three ways to provide an ID for fragment:

    • Provides a unique identity with the Android:id property.
    • Provides a unique string with the Android:tag property.
    • If neither of these properties is available, the system uses the ID of its container view.

You can also add fragment to an existing ViewGroup by using C # code.

You can add fragment to the activity layout at any time when the activity is running, and you simply need to specify the ViewGroup to place the fragment.

2. Create the fragment in the. cs file

To create a custom fragment class in a. cs file, you must inherit from the fragment class or its subclasses. The code implemented in the custom fragment class looks much like activity, such as rewriting OnCreate (), OnStart (), OnPause (), OnStop () 、...... such as In fact, if you replace a ready-made Android application with fragment, you can even port the code directly from the activity's callback method to the fragment callback method.

The following code is populated in the view with the Example_fragment.axml in the Inflate () method Resource/layout folder, and it is added as a child view within the grouping container.

public override View Oncreateview (layoutinflater inflater, ViewGroup container, Bundle savedinstancestate)

{

Return Inflater. Inflate (Resource.Layout.Example_Fragment, container, false);

}

Note: A child view that inherits from fragment must contain a default parameterless constructor.

3. Which methods need to be rewritten

During the fragment life cycle, you typically need to override (override) The following three callback methods in general: the Infalate () method, the OnCreate () method, the OnPause () method.

Most applications should implement these three methods at least for each fragment, but there are many other callback functions that manipulate the various stages of the fragment lifecycle. Callback functions in all life cycles are discussed later in the section on manipulating the fragment life cycle.

In addition to the base class fragment, here are a few subclasses you might inherit:

Dialogfragment: Displays a floating dialog box. Using this class to create a dialog box is a good alternative to using the Activity Class dialog help method, because you can incorporate the fragment dialog into the fragments background stack managed by the activity, allowing the user to return to an abandoned fragment.

Listfragment: Displays a list of entries managed by the adapter (for example, Simplecursoradapter), similar to listactivity. It provides a number of ways to manage the list view, such as Onlistitemclick ().

Preferencefragment: Displays a list of architectures for a preference object, similar to preferenceactivity. This is useful when creating "set up" activity for your application.

4. Add fragment to activity layout

Fragment are often used as part of the activity user interface and build their own layouts into activity.

In order to provide a layout for fragment, you must implement the Oncreateview () method, which is called by the Android system when drawing the fragment layout. To implement this method, you need to return the root view that fragment belongs to.

Note: If fragment is a subclass of Listfragment, it will return a ListView from Oncreateview () by default, so it does not need to be implemented again.

Typically, fragment constructs a partial interface to its host activity, which is embedded as part of the activity's full view hierarchy. There are two ways to add fragment in a acitivity layout:

(1) way to add fragment in the layout file

You can specify layout properties for fragment as you would specify layout properties for a view. For example:

<?xml version= "1.0" encoding= "Utf-8"?>

<fragment android:name= "Fragmentdemo.titlesfragment"

Android:id= "@+id/titles_fragment"

Android:layout_width= "Fill_parent"

android:layout_height= "Fill_parent"/>

The Android:name property in <fragment> specifies the fragment class that is instantiated in the layout.

When the system creates an activity layout, it instantiates each of the fragment specified in the layout file and calls the Oncreateview () function for them to get the layout of each fragment. The system inserts the view returned by the fragment directly at the location of the <fragment> element.

Note: Each fragment requires a unique identifier (ID), which is used to recover the fragment (and to capture fragment transactions, such as removal) if the activity is restarted.

There are three ways to provide an ID for fragment:

    • Provides a unique identity with the Android:id property.
    • Provides a unique string with the Android:tag property.
    • If neither of these properties is available, the system uses the ID of its container view.

You can also add fragment to an existing ViewGroup by using C # code.

You can add fragment to the activity layout at any time when the activity is running, and you simply need to specify the ViewGroup to place the fragment.

(2) Mode 2--add fragment to the. cs file

When adding fragment through code, you should use the Fragmenttransaction API to manipulate fragment in the activity (such as adding, removing, or replacing fragment). You can get an instance of fragmenttransaction from the activity as follows:

Fragmentmanager Fragmentmanager = new Fragmentmanager ()

Fragmenttransaction fragmenttransaction = this. Fragmentmanager.begintransaction ();

You can add fragment with the Add () function and specify the fragment to add and the view to which you want to insert it:

Examplefragment fragment = new Examplefragment ();

Fragmenttransaction.add (Resource.id.fragment_container, fragment);

Fragmenttransaction.commit ();

The first parameter of the incoming add () function is the viewgroup that fragment is placed on, which is specified by the resource ID (resource ID), and the second parameter is the fragment to be added.

The above code can also be written like this:

Examplefragment fragment = new Examplefragment ()

. ADD (Resource.id.fragment_container, fragment);

. Commit ();

Once the changes have been made through fragmenttransaction, commit () should be called to make the changes effective.

In addition, you can use fragment to provide background action for activity without rendering unnecessary user interfaces.

When adding a Fragment without an interface, it can be implemented by calling the Add (Fragment, String) method, which provides Fragment with a unique string "tag" instead of a view ID.

After adding fragment in this way, the activity does not call the Oncreateview () method because it is not associated with a view in the activity layout, so there is no need to rewrite Oncreateview () in the program.

Providing a string label for no-interface fragment is not specific to fragment without interfaces-it can also provide a string label for interface fragment-but for a no-interface fragment, the string label is the only way to recognize it. If you want to take fragment from the activity later, you need to use Findfragmentbytag (). Ii. handling of fragment affairs

A major feature of using fragment in activity is the ability to add, delete, replace, and perform other actions in response to user interaction. A series of changes submitted to the activity are referred to as transactions and can be handled using APIs in Fragmenttransaction.

You can also save each transaction in a background stack managed by activity and allow the user to navigate back fragment changes (similar to activity's fallback navigation).

You can get fragmenttransaction instances from Fragmentmanager, like this:

Fragmentmanager Fragmentmanager = new Fragmentmanager ();

Fragmenttransaction fragmenttransaction = Fragmentmanager.begintransaction ();

Because each transaction is a series of changes to be performed at the same time, you can set up all the changes you want to perform for a given transaction, such as Add (), remove (), and replace (). The transaction is then submitted to the activity using commit ().

However, before calling commit (), you might want to call ADDTOBACKSTATCK () in order to add the transaction to the fragment transaction background stack. This background stack is managed by the activity and allows the user to fall back to the previous fragment state by pressing the "Rewind" key.

The following code shows how to use another fragment instead of a fragment and leave the previous state in the background stack:

Create New Fragment and transaction

Fragment newfragment = new Examplefragment ();

Fragmenttransaction transaction = this. Fragmentmanager.begintransaction ();

Replace whatever is in the Fragment_container view with this fragment,

and add the transaction to the back stack

Transaction.replace (Resources.id.fragment_container, newfragment);

Transaction. Addtobackstack (NULL);

Commit the transaction

Transaction.commit ();

In this example, Newfragment replaces all of the fragment (if any) that are currently identified with Resources.id.fragment_container in the layout container, and the replaced transaction is saved in the background stack, so the user can roll back the transaction. You can restore the previous fragment by pressing the "Back" key.

If you add more than one change transaction, such as another add () or remove (), and call Addtobackstack (), then all changes to the app before calling commit () are added to the background stack as a separate transaction, and "Back" Keys can be rolled back together.

Note the following two points in order to add changes to the Fragmenttransaction:

    • You must call commit () at the end. If you are adding multiple fragment to the same container, the order of additions determines the order in which they appear in the View hierarchy (view hierarchy).
    • When you perform a delete fragment transaction, if you do not call Addtobackstack (), the transaction commits fragment is destroyed, and the user cannot fallback it. However, when a fragment is removed, if Addtobackstack () is called, then fragment will be stopped, and if the user rolls back, it will be restored.

Tip: For each fragment transaction, a series of transaction actions are applied by calling Settransition () before committing.

Calling commit () does not immediately execute the transaction, but instead takes an appointment, which can be run once the interface thread (main thread) of the activity is ready. However, if necessary, you can invoke Executependingtransations () from the interface thread to immediately execute the transaction committed by commit (). But doing so is usually not necessary unless the other thread's work depends on the transaction.

Warning: Transactions can only be committed with commit () before the activity is saved. If you try to commit after that time, an exception will be thrown. This is because if the activity needs to be restored, the status after the commit is lost. For this type of loss commit, it can be resolved by calling Commitallowingstateloss ().

1 , interacting with the activity

Although fragment is implemented as an object, it is independent of activity and can be used in multiple activity, a given fragment instance is bundled directly into the activity that contains it.

In particular, fragment can access activity through the getactivity () function, and it is easy to perform tasks similar to finding views in an activity layout:

View ListView = Activity.findviewbyid (Resources.id.list);

Similarly, activity can call fragment's function Findfragmentbyid () or Findfragmentbytag () to get the fragment index from Fragmentmanager, for example:

var fragment = (examplefragment) Fragmentmanager.findfragmentbyid (Resources.id.example_fragment);

2 , create event callback function for activity

In some cases, you may need to fragment to share events with the activity. A good way to do this is to define a callback interface inside the fragment and need the host activity to implement it. When activity receives a callback through an interface, it can share information with other fragment in the layout if necessary.

For example, if there are two fragment--in the actvity of the news app, one shows the list of articles (fragment a), the other shows an article (fragment B)--and then fragment a must tell the activity list when the item is selected, so , activity can notify fragment B to display this article. In this case, the interface Onarticleselectedlistener is declared inside fragment a:

public static Class Fragmenta:listfragment

{

...

Container Activity must implement this interface

public interface Onarticleselectedlistener

{

public void onarticleselected (Uri articleuri);

}

...

}

The host activity of the fragment then implements the Onarticleselectedlistener interface and overrides Onarticleselected () to notify fragment B of events from fragment a. To ensure that the host activity implements this interface, fragment A's Onattach () callback function (which is called by the system when adding fragment to the activity) passed in as a parameter to the Onattach () The type conversion of the activity to instantiate a Onarticleselectedlistener instance.

public static Class Fragmenta:listfragment

{

Onarticleselectedlistener Mlistener;

...

public override void Onattach (activity activity)

{

Base. Onattach (activity);

try {

Mlistener = (onarticleselectedlistener) activity;

} catch (ClassCastException e) {

throw new ClassCastException (activity.tostring () + "must implement Onarticleselectedlistener");

}

}

...

}

If the activity does not implement this interface, then fragment throws a Classcaseexception exception. Once successful, the Mlistener member retains a reference to the activity's Onarticleselectedlistener implementation, thus fragment A can share events with activity by invoking methods defined by the Onarticleselectedlistener interface. For example, if fragment A is a subclass of Listfragment, the system calls the Fragment Onlistitemclick () event each time the user taps the list item, and then fragment calls Onarticleselected () To share events with the activity.

public static Class Fragmenta:listfragment

{

Onarticleselectedlistener Mlistener;

...

public override void Onlistitemclick (ListView l, View v, int position, long ID) {

Append the clicked item ' s row ID with the content provider Uri

Uri Noteuri = Contenturis.withappendedid (Articlecolumns.content_uri, id);

Send the event and Uri to the host activity

Mlistener.onarticleselected (Noteuri);

}

...

}

The parameter ID passed to Onlistitemclick () is the clicked list item row id,activity (or other fragment) to get the article from the app's ContentProvider.

More information about using content provider is available in the Content providers documentation.

3 , add items to the menu item

Your fragments can build the menu item to the Activity's Options menu (as well) by implementing Oncreateoptionsmenu (). In order to receive the call using this method, you must call Sethasoptionsmenu () during oncreate () to indicate the fragment you want to add the item to the Options menu (otherwise, Fragment will not receive a call to Oncreateoptionsmenu ().

Any items that you want to add to the Options menu in fragment are appended to the existing menu items. When the menu item is selected, fragment also receives a callback to the onoptionsitemselected ().

You can also register a view in the fragment layout by calling Registerforcontextmenu () to provide a right-click shortcut menu (Context menu). When the user opens the context menu, fragment receives a callback to Oncreatecontextmenu (). When the user selects an item, fragment receives a callback to oncontextitemselected ().

Note: Although your fragment will receive a callback for the menu item that is selected for each menu item, the activity will first receive the corresponding callback when the user selects a menu item. If the implementation of the activity's Select menu item callback does not handle the selected item, then the event is passed to the fragment callback. The same applies to Options menu and context menu.

For more information about menus, refer to the menu and Action Bar Development Guide. Third, to deal with the life cycle of fragment

Managing the Fragment life cycle is similar to managing the activity life cycle. Like activity, fragment also has three states:

    • Resumed:fragment is visible in the running activity.
    • Paused: Another activity is in the foreground and gets the focus, but the activity of the fragment is still visible (the foreground activity is partially transparent or not covered in full screen).
    • Stopped:fragment not visible. Either the host activity has stopped, or fragment has been removed from the activity but has been added to the background stack. A stopped fragment is still alive (all state and member information is still kept by the system). However, it is no longer visible to the user and will be killed if the activity is killed.

Similarly to activity, you can also use bundles to save the fragment state, in case the activity process is killed, and you need to restore the fragment state when the activity is recreated. The state can be saved during the callback execution fragment Onsaveinstancestate (), which can be restored in OnCreate (), Oncreateview (), or onactvitycreate (). For more information on saving status, refer to the activities documentation.

1, the Management fragment life cycle

In the life cycle, an important difference between activity and fragment is how it is stored in its own background stack. When activity is stopped, activity is placed in the system-managed activity background stack by default (so the user can press the "back" key to rollback the navigation, as discussed in the tasks and background stacks). However, the fragment is placed in the background stack managed by the host activity only if you request the saved instance explicitly by calling Addtobackstack () when a transaction is removed.

In addition, the life cycle of managing fragment is very similar to the life cycle of managing activity. Therefore, the practice of managing the activity life cycle also applies to fragment. What you need to know is just how the life cycle of the activity affects fragment.

2 and coordination with the activity life cycle

The activity life cycle of fragment directly affects the life cycle of fragment, thus triggering a fragment similar callback for each life cycle callback of the activity. For example, when activity receives OnPause (), each fragment in the activity receives OnPause ().

Fragment has some additional life-cycle callback methods, however, it interacts with the activity in order to deal with the fragment interface, such as creating and destroying it. These additional callback methods are:

Onattach (): Called when fragment is bound to activity (activity is passed in).

Oncreateview (): Called when creating a view system related to fragment.

Onactivitycreated (): Called when the activity's OnCreate () function returns.

Ondestroyview (): Called when the view system associated with fragment is being removed.

Ondetach (): Called when fragment is being disassociate from activity.

Detailed descriptions of these methods are shown in section 11.4.

The life cycle process of fragment is actually affected by its host activity. For example, when the activity receives its oncreate () callback, the fragment in the activity receives only the onactivitycreated () callback.

Once the activity is in the resumed state, you can freely add or remove fragment in the activity. Therefore, the life cycle of fragment can change independently only when the activity is in the resumed state.

However, when activity leaves the recovery state, fragment is once again pushed into its life cycle by activity. Iv. a few special fragment classes

The Fragments API provides the following subclasses, which can be used to implement some common functionality. These classes are:

    • Listfragment– uses fragment as a list item.
    • dialogfragment– displays the fragment as a dialog box.
    • preferencefragment– displays the fragment as a series of preferences.

In the next section we will demonstrate the basic usage of fragment with specific examples.

"Android" 11.5 Create and manage fragments

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.