Android Api Component --- Fragment Component translation (1)

Source: Internet
Author: User

Android Api Component --- Fragment Component translation (1)

Fragment represents one or more actions in an Activity. You can connect multiple fragment in a single activity to build a multi-panel UI, in addition, one fragment is used repeatedly in multiple activities. You can think of fragment as a modular part of the activity. It has its own lifecycle and receives its own input events, you can also add or remove fragment when the activity is running.


An frgment must be embedded in an activit, And the lifecycle of this fragment is directly affected by the lifecycle of its main activity. For example, when an activity is paused, its fragment will also be paused. When the activity is destroyed, its fragment will also be destroyed. However, when the activity is running (it restores the lifecycle state), you can maintain each fragment independently, such as adding or removing them. When you execute such a fragment event, you can add it to the rollback stack managed by the activity. Each rollback stack in the activity records the occurrence of the fragment event. By pressing the return button, roll back the stack to allow the user to return a fragment event (navigation backward ).


When the fragment you add is part of the activity layout, it resides in a ViewGroup of the activity's view structure, and fragment defines its own layout. You can define fragment in the activity layout file to insert it into your activity, like Or add it to an existing ViewGroup through the code in your application. However, a fragment does not have to be part of the activity layout. You can also use a fragment without UI as an invisible worker in the activity.


This document describes how to use fragment to build your applications, including how fragment maintains their status when the fragment is added to the rollback stack of the activity, it also shares events with the activity, other fragment in the activity, and the actionbar contributed to the activity.


Design Philosophy

Android 3.0 introduced fragment, mainly to support more dynamic and fixed uidesigns on the screen, such as tablets. Because the screen size of a tablet is larger than that of a handheld device, more space connections are available and the screen size interacts with the UI components. Such a fragment design allows you to avoid managing complex view structures. By separating activity la s into fragment, you can modify the appearance of the activity at runtime and maintain these changes in the rollback stack of activity management.


For example, a news application can use one fragment to display a list of articles on the left, and the other fragment to display articles on the right. Both fragment appear in the same activity and are next to each other, each fragment has its own lifecycle callback method and its own user input events. Therefore, instead of using activity to select an article and another activity to read this article, you can select an article in the same activity and read the article. Illustrations on the tablet


You should design fragment into a modular and reusable activity component. That is to say, since each fragment defines its own layout and uses its own lifecycle callback to define its own behavior, you can include one fragment in multiple activities. This is very important because a modular fragment allows you to change your fragment to connect screens of different sizes. When designing your applications that support both tablets and handheld devices, you can reuse your fragment in different layout configurations based on valid screen space to optimize user experience. For example, on a handheld device, when more than one fragment is available in the activity, fragment may need to be separated to provide a single UI.


For example-continue to use the news application example-when running on A tablet-sized device, the application can embed two fragment entries in activity. However, on a handheld screen, there is not enough space for two fragment. Therefore, the Activity contains a unique fragment for the article list. When you select an article, Activity B is enabled, this activity contains the second fragment to read this article. Therefore, different combinations are used to reuse fragment. The application supports both flat and handheld devices.


Use different fragment combinations to design your applications for different screen configurations. For more information, see Supporting Tablets and Handsets.


Create a Fragment


To create a Fragment, you must create a subclass of Fragment (or its subclass ). The Code of Fragment looks very similar to that of activity. The callback method is similar to the Activity method. Such as onCreate (), onStart (), onPause (), and onStop (). In fact, if you use fragment to convert an existing Android Application, you can simply move the code from your activity callback Method to the corresponding fragment callback method.

Generally, you should implement at least the following three methods in the lifecycle:


OnCreate ()

This is called when fragment is created. In your implementation, you should initialize the components required by fragment. This component is recycled when your fragment is paused or stopped, and then restored.


OnCreateView ()


When fragment draws its UI for the first time, the system calls it. To draw the UI for your fragment, you must return the root View of your fragment layout from this method. If fragment does not provide the UI, you can return null.


OnPause ()


The system calls the fragment when it detects that the user is leaving the fragment. This method should be implemented through the current user session, which is usually where you should submit the data that should be persistent.


Most applications should implement at least three methods for each fragment, but there are several other callback methods you should also use to operate on different stages of the fragment lifecycle. All Lifecycle callback methods are discussed in detail in Handling the Fragment Lifecycle.


There are also several subclasses that you may want to extend to replace the Fragment base class:


DialogFragment

A floating dialog box is displayed. Using this class creation dialog box, using the dialog box helper method in the Activity class is a good choice. Because you can merge a fragment dialog box into the rollback stack managed by activity. Allowing the user to return to a dismissed fragment (pending first ).


ListFragment

Displays a list of items managed by the adapter (such as SimpleCursorAdapter), which is similar to ListActivity. It provides several methods to manage the list view, such as the onListItemClick () callback to hold the click event.


PreferenceFragment


Displays the structure list of a Preference object, similar to PreferenceActivity. It is valid to create a "settings" activity in your application.


Add a user interface

A fragment is usually used as part of the user interface of the activity and provides its layout to the activity. To provide a layout for a fragment, you must implement an onCreateView () callback method. When fragment draws its layout, this method is called, the implementation of your method must return the root View of your fragment layout.


NOTE: If your fragment is a subclass of ListFragment, A ListView is returned by default from onCreateView (), so you do not need to implement it.


To return a layout from onCreateView (), you can populate it with a defined layout resource in XML. To help you do this, onCreateView () provides a LayoutInflater object.


For example, this is a Fragment subclass that loads a layout from the example_fragment.xml file:

public static class ExampleFragment extends Fragment {        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {        return inflater.inflate(R.layout.example_fragment,false);    }}

The parameter passed to the container is the parent ViewGroup (from the layout of the Activity). In this ViewGroup, your fragment layout is inserted. The savedInstanceState parameter is a Bundle. If the fragment is restored, this object provides the data of the previous fragment instance.


Inflate () has three parameters:


ID of the layout you want to fill in

ViewGroup is the parent ViewGroup of the filled layout. It is important to pass the container to the Root View of the specified parent view layout to apply the layout parameters of the system.

A boolean value that checks whether the layout filled during filling should be bound to the ViewGroup (second parameter ).


Now you have seen how to create a fragment with a layout. Next, you need to add the fragment to your activity.


Add a fragment in the activity

In general, fragment provides a part of the UI for the main activity, which is embedded as part of all the view structures of the activity. You can add a fragment to the activity layout in two ways.


Define fragment in the activity layout file.

In this example, you can specify layout attributes for the fragment view. For example, two fragment elements in the following layout file constitute an activity:

 
         
      
          
 


In The android: name attribute in specifies the Fragment class to be instantiated in the layout. When the system creates the activity layout, it initializes each fragment specified in the layout and calls the onCreateView () method for each fragment to obtain the layout of each fragment. System insert directly returned by fragment View of the element.


Note: If the activity is restarted (and you can use it to get fragment to execute things, like removing it), each fragment requires a unique system to restore the fragment identifier. There are three ways to provide an ID for fragment:

Android: The id attribute supports a unique ID.

Android: The tag attribute supports unique IDs.

If you do not provide the preceding two attributes, the container view ID is used.


Alternatively, add fragment to an existing ViewGroup programmatically.

At any time, when your activity is running, you can add fragment to your activity layout. You only need to specify a ViewGroup for fragment in this activity.

You must use the FragmentTransaction API to create fragment items (such as adding, removing, and replacing a fragment) in your activity. You can get the FragmentTransaction instance from your Activity, like this:

FragmentManager fragmentManager = getFragmentManager();FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

Then you can use the add () method to add a fragment, specify the fragment to add, and use this view to insert it. For example:

ExampleFragment fragment = new ExampleFragment();fragmentTransaction.add(R.id.fragment_container,fragment);fragmentTransaction.commit();

The first parameter passed to add () is to place the frament ViewGroup with the specified resource ID, and the second parameter is the fragment to be added.


Once you make a change using FragmentTransaction, you must call commit () to make the change take effect.


Add a fragment without a UI

The preceding example shows how to add a fragment to your activity to provide a UI. However, you can use a fragment to provide a background behavior for this activity without any additional UI.


To add a fragment without a UI, use add (Fragment, String) to add fragment from the activity (provide a unique String "tag" for fragment, rather than a view ID ). This adds fragment. However, since it is not associated with a view in the activity layout, it will not receive a call from onCreateView. Therefore, you do not need to implement this method.


It is not mandatory to provide a string tag for non-UI fragment. You can also provide a string tag for the fragment with UI-but if fragment has no header UI, the string tag is the only way to identify it. If you want to obtain fragment from the activity in the future, you need to use findFragmentByTag ().


Manage fragment

To manage fragment in your activity, you need to use FragmentManager. To get it, call getFragmentManager () from your activity ().


You can use FragmentManager to do the following:

Use findFragmentById () (fragment for the UI provided in the activity layout) or findFragmentByTag () (for fragment without the UI) to obtain the fragment existing in the activity.

Use popBackStack () to pop up fragment from the rollback stack.

Register a listener with addOnBacktackChangeListener () to roll back the stack.


For more information about those methods and others, see the FragmentManager Class documentation.


As shown in the previous snippet, you can also use FragmentManager to open a fRAGMENTtRANSACTION. This FagmentTransaction allows you to execute a transaction like adding or removing frament.


Execute the Fragment transaction

One of the bigger features of using fragment in your activity is that you can use these fragment to add, remove, replace, and execute other actions in your user interaction. Every change you submit to the activity calls a transaction and you can use the FragmentTransaction API for execution. You can also save each transaction to a rollback stack managed by the activity and allow the user to navigate the rollback through the change in fragment (similar to the rollback through the activity ).


You can request a FragmentTransaction instance from FragmentManager, such:

FragmentManager fragmentManager = getFragmentManager();FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();


Each transaction is a group of changes you want to execute at the same time. You can set all the changes you want to execute for a given transaction using the add (), remove (), and replace () methods. Then, to apply the transaction to this activity, you must call commit ().


Before you call the commit () method, you may want to call addToBackStack () to add a transaction to the rollback stack of a fragment transaction (). This background site is managed by this activity and allows users to return to the previous fragment status by pressing the return button.


For example, the following example replaces another fragment with one fragment and maintains the state of migration in the rollback Stack:

//Create new fragment and transactionFragment newFragment = new ExampleFragment();FragmentTransaction transaction = getFragmentManager().beginTransaction();//Replace whatever is in the fragment_container view with this fragment,//and add the transaction to the back stacktransaction.replace(R.id.fragment_container,newFragment);transaction.addToBackStack(null);//Commit the transactiontransaction.commit();

In this example, No matter what fragment is in the current layout file, newFragment replaces it with the id of marked R. ID. fragment_container. You can call addToBackStack () to replace a transaction in the rollback stack. Therefore, you can maintain the transaction and press the return button to return to the previous fragment.


If you add multiple changes to a transaction (such as another add () or remove () and call addToBackStack (), all changes applied before you commit will be added to the rollback stack as a separate transaction, and the return button will roll back them together.


The sequence you add to a FragmentTransaction clock is irrelevant:

You must call commit ()

If you add multiple fragment to the same container, the training you add them determines the order in which they appear in the view structure.


When you execute a transaction to remove a fragment, if you do not call addToBackStack (), the fragment will be destroyed when the transaction is committed, the user cannot navigate back to the previous fragment. If you call addToBackStack () when removing a fragment, the fragment will stop and be restored if the user navigation rolls back.


Suggestion: before committing each fragment transaction, you can call setTranction () to apply the transaction animation.


Calling commit () does not execute transactions immediately. Of course, it will be scheduled to be executed in the UI thread of the activity. If necessary, you can call executePendingTransaction () from your UI thread to immediately execute the transaction committed through commit. This is usually not required unless the transaction is dependent on tasks in other threads.


Note: You can use commit () to submit a transaction. This action takes precedence over the action in which the activity saves its status. If you try to submit after that point, an exception will be thrown. This is because if the activity needs to be restored, the submitted status may be lost. In this case, you can use commitAllowingStateLoss () to record your lost commit.

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.