Android Fragment (website information translation)

Source: Internet
Author: User
Tags unique id

fragment points fragment as part of the activity interface, multiple fragment can appear in one activity, and a fragment may be used in multiple activity. While the activity is running, you can add, remove, or replace fragment (add (), remove (), replacement ()) fragment can respond to your own input events and have their own life cycle, of course, Their life cycles are directly affected by the life cycle of the host activity to which they belong. Design philosophy Android introduced the concept of fragments in 3.0, the main purpose is to use on large-screen devices-for example, on tablets, support for more dynamic and flexible UI design. Tablet screens are much larger than phones, have more room to put more UI components, and create more interaction between these components. Fragment allows such a design without requiring you to manage the complex changes of viewhierarchy in person. By dispersing the layout of the activity into fragment, you can modify the appearance of the activity at run time and save those changes in the back stack managed by the activity. (http://developer.android.com/guide/topics/fundamentals/fragments.html)For example, a news app can use a fragment on the left side of the screen to display a list of articles, and then use another fragment on the right side of the screen to show an article--The 2 fragment are displayed side by side in the same activity, and each fragment has its own set of lifecycle callback methods and handles their own user input events. Thus, instead of using an activity to select an article and another activity to read the article, the user can select an article in the same activity and read: Fragment should be a modular and reusable component in your application. That is, Because fragment defines its own layout and defines its own behavior by using its own lifecycle callback method, you can include fragment in multiple activities. This is especially important because it allows you to adapt your user experience to a different screen size. For example, you might have more than one fragment in an activity when the screen size is large enough, and when this is not the case, another individual is started,     Use different fragment of activity. To continue the example of the previous news-- When running on a particularly large screen, such as a tablet, an app can embed 2 fragment in activity A. However, on a normal-sized screen (such as a mobile phone), there is not enough space for 2 fragment, so Activity A will only contain the fragment of the article list, and when the user selects an article, it will start Activityb, It contains the fragment to read the article. As a result, applications can support 2 design patterns in the same way. Create Fragment to create a Fragment, you must create a subclass of Fragment (or inherit from a subclass of it that already exists). The code for the Fragment class looks much like Activity. It contains callback methods similar to activity, such as OnCreate (), OnStart (), OnPause (), and OnStop ().          In fact, if you're going to switch from an off-the-shelf Android app to using fragment, you can simply move the code from your activity's callback method to your fragment callback method. In general, you should implement at least the following life cycle methods: OnCreate () This method is called when the fragment is created. In the implementation code, you should initialize the necessary components that you want to keep in fragment, which can be resumed when fragment is paused or stopped. Oncreateview () Fragment This method is called the first time the user interface is drawn. In order to draw the fragment UI, this method must return a view, which is the root view of your 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 fragment will be destroyed.) Before the end of the current user session, You should usually submit any changes that should persist here (because the user may not return). The life cycle diagram is as follows: Most applications should implement at least these 3 methods for each fragment,      But there are other callback methods you should also use to deal with the various stages of the Fragment life cycle. The entire lifecycle callback method will be discussed in later chapters Handlingthe Fragment Lifecycle. In addition to inheriting the base class Fragment, there are some subclasses you might inherit: dialogfragmentDisplays a floating dialog box. Using this class to create a dialog is a good choice to use outside of the Activity class's dialog tool method, because you can merge a fragment dialog box into the activity-managed fragment back stack. Allows the user to return to a previously abandoned fragment. Listfragment displays a list of items that are managed by a adapter (for example, Simplecursoradapter), similar to listactivity. It provides methods to manage a list view, such as Onlistitemclick () callback to handle the Click event. Preferencefragment displays a list of hierarchies for a preference object, similar to preferenceactivity. This creates aSettingsuseful when doing activity. Add a user interface fragment is typically used as part of an activity's user interface and provides its layout to the activity. To provide a layout for a fragment, you must actually        Now Oncreateview () callback method, when the fragment draw its own layout, the Android system calls it. Your implementation code for this method must return a root view of your fragment layout.        Note: If your fragment is a subclass of Listfragment, its default implementation is to return a ListView from Oncreateview (), so it is generally not necessary to implement it. The view returned from Oncreateview () can also be read and generated from a layout XML resource file.      To help you do this, Oncreateview () provides a Layoutinflater object. For example, here is a subclass of fragment, loaded from file Example_fragment.xml with a Layout:[java] view plaincopy Public Static classExamplefragmentextendsFragment {@Override PublicView Oncreateview (layoutinflater inflater, ViewGroup container, Bundle Savedinstancesta TE) {//inflate the layout for this fragment        returnInflater.inflate (R.layout.example_fragment, container,false); The container parameter of the incoming Oncreateview () is your fragmentlayout will be inserted by the parent viewgroup (from the activity's layout) savedinstancestate parameter is a bu Ndle, if fragment is restored, it provides data about the previous instance of fragment, and the inflate () method has 3 parameters: the resource of the layout you want to load ID. The parent viewgroup of the loaded layout. The incoming container is important to allow the system to accept the layout parameter of the root view of the layout to be loaded, specified by the parent view that it will be anchored to. A Boolean value indicates that during load Whether the expanded layout should be attached to ViewGroup (the second parameter). (In this example, FALSE is specified because the system has inserted the expanded layout into container– to pass true to create an extra view group in the final layout.) Adding fragment to activity typically, fragment provides a part of the UI for the host activity and is embedded as part of the entire viewhierarchy of activity. There are 2 ways you can add a fragment to activity layout: Declare fragment in the activity's layout file in this case, you can be like a view, Specifies the layout property for fragment. An example is the layout of an activity with 2 fragment: [HTML] View plaincopy<?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> <fragment>The Android:name property in specifies the fragment class that is instantiated in layout. When the system creates this activity layout, it instantiates each of the fragment specified in layout and invokes the Oncreateview () method on each one to get each Fragment layout. The system will insert the view returned from the fragment directly into the<fragment>where the element resides.   Note: Each fragment requires a unique identity, and if the activity restarts, the system can be used to recover the fragment (and you can also use it to capture fragment to handle 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 you have provided, The system uses the ID of the container view. The compose code adds fragment to an existing viewgroup. You can add fragment to an activity when the activity is running Layout. Simply specify a viewgroup to place fragment. To manipulate fragment transactions in your activity (for example, add, remove, or replace a fragment),       You must use an API from Fragmenttransaction. You can get an instance of fragmenttransaction from your activity as follows: [Java] View plaincopy 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. [Java] View plaincopy examplefragment fragment=newexamplefragment ();  Fragmenttransaction.add (r.id.fragment_container,fragment);        Fragmenttransaction.commit (); The first parameter of add () is the fragment to put in the ViewGroup, specified by the resource ID, and the second parameter is the fragment that needs to be added. Once a change has been made with fragmenttransaction, in order for the change to take effect, Commit () must be called. Adding a fragment without UI shows the support for the UI and how to add a fragment to the activity. However,    You can also use fragment to provide background behavior for activity without showing additional UI. To add a Fragment without UI, you need to add Fragment from activity using Add (Fragment, String) (provides a unique string for Fragment"Tag"=Getfragmentmanager (); Fragmenttransaction fragmenttransaction=fragmentmanager.begintransaction ();  Each transaction is a set of changes to be performed at the same time. You can set all the changes you want to perform in a given transaction, using such things as add (), remove (), and replace (). Then, to apply a transaction to the activity, you must call commit (). Before calling commit (), you might want to call Addtobackstack () to add a transaction to the backstack of a fragment transaction.       This back stack is managed by the activity and allows the user to return to the previous fragment state by pressing the home button. For example, here's how to replace one fragment with another and keep the previous state in the background stack: [Java] View plaincopy//Create new Fragment and transactionFragment newfragment =newexamplefragment (); Fragmenttransaction Transaction=Getfragmentmanager (). BeginTransaction (); //Replace Whatever is in Thefragment_container view with this fragment,//And Add the transaction to the BackstackTransaction.replace (r.id.fragment_container,newfragment); Transaction.addtobackstack (NULL); //Commit The transactionTransaction.commit (); In this example, Newfragment replaces the fragment identified by R.id.fragment_container in the current layout container. By calling Addtobackstack (), the Replace transaction is saved to the back    Stack, so the user can roll back the transaction and bring back the previous fragment by pressing the return key.       If you add multiple changes to a transaction (such as add () or remove ()) and call Addtobackstack (), then any changes to the app before you call commit () will be added to the background stack as a single transaction, and the back button will rewind them together.    The order of adding changes to fragmenttransaction is not important, except for the following exception: Commit must be called last (). If you add multiple fragment to the same container, the order in which they are added determines the order in which they appear in the view hierarchy. When executing a transaction that removes fragment, if Addtobackstack () is not called, then when the transaction commits, that fragment is destroyed and the user cannot navigate back to it.      In view of this, when a fragment is removed, if Addtobackstack () is called, then fragment is stopped and if the user navigates back, it will be restored.    Tip: For each fragment transaction, you can apply a transaction animation by invoking the settransition () implementation before committing the transaction. Calling commit () does not execute the transaction immediately. On the contrary, it schedules the transaction and, once ready, runs on the activity's UI thread (the main thread). If necessary, anyway, You can invoke Executependingtransactions () from your UI thread to immediately execute the transaction committed by commit ().     This is usually unnecessary, unless the transaction is a subordinate to a task in another thread. Warning: You can only commit a transaction using commit () before the activity saves its state (when the user leaves activity). Communicating with activity Although fragment is implemented as an activity-independent object, And can be used in multiple activity, but a given fragment instance is directly bound to the activity that contains it. In particular, fragment can be used Getactivity () Accesses the activity instance and easily performs tasks such as finding a view in activity layout.  [Java] View Plaincopy view ListView=getactivity (). Findviewbyid (r.id.list); <span style= "Font-family:system;" > </span>Similarly, activity can invoke a method in fragment by obtaining a reference to fragment from Fragmentmanager, using Findfragmentbyid () or Findfragmentbytag ( ). [Java] View plaincopy examplefragment fragment=(examplefragment) Getfragmentmanager (). Findfragmentbyid (r.id.example_fragment); Create an event callback method for activity in some cases, you may need a fragment to share events with the activity.    A good approach is to define a callback interface in fragment and require the host activity to implement it. When activity receives a callback through interface, it can share information with other fragment in layout if necessary. For example, if a new app has 2 fragment– in activity to display a list of articles (Framgent a) and another to display the article content (fragment B) – then framgent a must tell the activity when a list ite    M is selected, and then it can tell FRAGMENTB to show the article. In this example, the Onarticleselectedlistener interface is declared in fragment a: [Java] View plaincopy Public Static classFragmentaextendslistfragment {...//Container Activity must implement this interface     Public InterfaceOnarticleselectedlistener { Public voidonarticleselected (Uri Articleuri);             }      ...  } The host activity of the fragment then implements the Onarticleselectedlistener interface and overwrite onarticleselected () to notify fragment B, from fragment A coming event. To ensure that the host activity implements this interface, fragment A's Onattach () callback method (called by the system when adding fragment to activity) passed as a parameter to the Onattach () Activity does the type conversion to instantiate a Onarticleselectedlistener instance. [Java] View plaincopy Public Static classFragmentaextendslistfragment {Onarticleselectedlistener mlistener; ... @Override Public voidOnattach (activity activity) {Super. Onattach (activity); Try{Mlistener=(Onarticleselectedlistener) activity; } Catch(classcastexception e) {Throw NewClassCastException (activity.tostring () + "must Implementonarticleselectedlistener");            }      }         ...     } If the activity does not implement an interface, fragment throws an ClassCastException exception. Under normal circumstances, the Mlistener member maintains a reference to the activity's Onarticleselectedlistener implementation, so fragment A can share events to the activity by invoking methods defined in the Onarticleselectedlistener interface. For example, if fragment A is a subclass of Listfragment, each time a user taps a list item, The system calls Onlistitemclick () in fragment, and then the latter calls onarticleselected () to assign the event to the activity. [Java] View plaincopy Public Static classFragmentaextendslistfragment {Onarticleselectedlistener mlistener; ... @Override Public voidOnlistitemclick (ListView L, View V,intPositionLongID) {//Append The clicked item ' s row ID with the content provider UriUri Noteuri =Contenturis.withappendedid (Articlecolumns.content_uri, id); //Send the event and Uri to the host activitymlistener.onarticleselected (Noteuri);      }         ...     } The ID parameter passed to Onlistitemclick () is the row ID of the item being clicked, and activity (or other fragment) is used to get the article from the ContentProvider of the app. Add items to Actionbar your fragment can provide menu items to activity by implementing Oncreateoptionmenu () (and so on, Action bar). In order for this method to receive calls, anyway, you    You must call Sethasoptionsmenu () during onCreate () to indicate that fragment is willing to add item to the Options menu (otherwise, fragment will not receive a call to Oncreateoptionsmenu (). Any items that are subsequently added from fragment to the option menu are appended to the existing menu item. When a menu item is selected, fragment also receives a callback to the onoptionsitemselected (). It can also be in your fragment A view is registered by calling Registerforcontextmenu () in layout to provide an environment menu. When the user opens the Environment menu, fragment receives a pair of Oncreatecontextmenu ()    Call. When the user selects an item, fragment receives a call to Oncontextitemselected (). Note: Although your fragment will receive a callback for each menu item that it adds, the activity will first receive the corresponding callback when the user chooses a menu item. If the activity's on-item-selected callback function implementation does not process the selected item, and then the event is passed to the fragment callback. This rule applies to the options menu and the Environment menu. Managing the life cycle of the fragment lifecycle management fragment, most places are much like the management activity life cycle. Like activity, fragment can be in 3 states: resumed in a running activity fr   Agment visible.   Paused another activity is in the foreground and has the focus, but the activity of the fragment is still visible (the foreground activity is partially transparent or does not cover the entire screen).        Stopped either the host activity has been stopped, or the fragment is removed from the activity but added to the background stack. The fragment of the stop State is still alive (all state and member information is maintained by the system). However, it is no longer visible to the user, and if the activity is killed, he will be killed. The corresponding diagram is as follows: As with activity, you can use bundles to keep the fragment state, in case the activity process is killed, And when the activity is re-created, you need to restore the state of fragment.      You can save the state during Fragment's onsaveinstancestate () and restore it during onCreate (), Oncreateview (), or onactivitycreated (). The most important difference between activity and fragment in the life cycle is how each is stored in its back-end stack. By default, when activity is stopped, it is placed in a system-managed background stack to hold activity.      (So the user can use the Back button to navigate backward to it).    However, when you remove fragment during a transaction, explicitly calling Addtobackstack () requests to save the instance is placed into a background stack managed by the host activity. In addition, managing the fragment life cycle is very similar to managing the activity life cycle. Therefore, the "Managing the Activitylifecycle"also applies to fragment. What you need to understand is how the life of the activity affects fragment's life. Coordinating work with the activity life cycle fragment the life cycle of the activity that survives,       Directly affects the life cycle of the fragment, and the callback behavior of each activity's life cycle causes a similar callback in each fragment.       For example, when an activity receives a onpause (), each fragment in the activity receives OnPause (). Fragment has some additional life-cycle callback methods, those that are the only interactions with the activity, in order to perform actions such as creating and destroying Fragment UI. These additional callback methods are: Onattach () is called when fragment is bound to the activity (the activity is passed in.). Called when Oncreateview () creates and fragment associated view hierarchy. onactivitycreated () is called when the OnCreate () method of the activity returns. Ondestroyview ()       Called when the view hierarchy associated with fragment is being removed. Ondetach () Called when fragment is disassociate from activity. The process of the fragment life cycle, and the impact that the host activity has on it, is shown in Figure 3. In this diagram, you can see how each state of activity in turn determines the callback method that fragment might receive. For example,       When the activity receives its oncreate (), the activity fragment receives a maximum of onactivitycreated ().       Once the activity reaches the resumed state, you are free to add and remove fragment from the activity. Therefore, the life cycle of fragment can change independently only when the activity is in resumed state. In any case, when activity leaves the resumed state, fragment is again pushed into its own life cycle by the activity.

Android Fragment (website information translation)

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.