Definition
- A Fragment represents a behavior or a potion of user interface in an Activity.
- You can combile multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple Activiti Es.
- A Fragment have its own life cycle, receives its own input events, and you can add or remove it while the activity is Runni Ng. (Sub activity)
- A Fragment ' s lifecycle is directly affected by its host activity ' s lifecycle. It follows the activity ' s lifecycle, except for in resuming state. The fragment ' s transaction can be pushed into the backstack.
Ways to add a fragment to Acitvity
- Define <fragment>...</fragment> in Layout file.
- In code, add a fragment to an existing viewgroup.
Design Philosophy
- Appears in 3.0 (API 11) to meet dynamic, flexible UI designs that avoid frequent changes in view hierarchy.
- For fragment A to be reused, try to avoid operating its life cycle in another fragment B (because it is likely that there is no B in another scenario)
Creating a Fragment
When implementing a fragment, it is often necessary to override the following methods
- OnCreate (), completion of initialization function
- Oncreateview (), fragment the method is called when the UI is first drawn, returns the root view, or null if fragment does not need the UI
- OnPause (), Commit changes
Several fragment
- Dialogfragment
- Listfragment
- Preferencefragment
Several ways to create fragment
- declaration in the layout file
<android:name= "Com.example.news.ArticleListFragment" Android:id = "@+id/list" android:layout_weight= "1" android:layout_width= "0DP" android:layout_height= "match_parent"/>
- Programmatically (in Activity)
Fragmentmanager fm ==new samplefragment (); Ft.add (R.id.fragment_container, F); Fm.commit ();
Fragment with no UI
- Add using Add (Fragment Fragment, String tag)
- No need to rewrite the Oncreateview method
- Use Findfragmentbytag to get the fragment
Managing Fragments
The role of Fragmentmanager
- Get Fragment:findfragmentbyid (with UI), Findfragmentbytag (no UI)
- Make fragment out of the stack, Popbackstack (), impersonate the user by clicking the Back button. (What's the use?) )
- Add Listener,addonbackstackchangelistener () to Backstack
Performing Fragment transactions
Use Backstack to store the state of fragment
// Create new Fragment and transaction New = getfragmentmanager (). BeginTransaction (); // Replace Whatever is in the Fragment_container view with this fragment, // And Add the transaction to the back stack transaction.replace (R.id.fragment_container, newfragment); Transaction.addtobackstack (null ); // Commit The transactiontransaction.commit ();
Use Settransaction () before commit () to add animation effects
Communicating with the Activity
Get references from each other
- Fragment using Getactivity () to obtain a reference to the host activity
- Activity gets the embedded fragment reference by Getfragmentmanager (). Findfragmentbyid ()
Implement the callback of the activity in fragment: Declare an interface, save the activity reference of the interface at Onattach () and invoke the method in the interface when you need to notify the activity
Public Static classFragmentaextendsListfragment {
Private Onarticleselectedlistener Mlistener; ... //Container Activity must implement this interface Public InterfaceOnarticleselectedlistener { Public voidonarticleselected (Uri Articleuri); } ... @Override Public voidOnattach (activity activity) {Super. Onattach (activity); Try{Mlistener=(Onarticleselectedlistener) activity; } Catch(classcastexception e) {Throw NewClassCastException (activity.tostring () + "must implement Onarticleselectedlistener"); }} ... @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); } ...}
Fragment can register Options menu and context menu to receive onoptionsitemselected () and other events
Handling the Fragment Lifecycle
Fragment life cycle is similar to activity
- Create phase, Onattach (), OnCreate (), Oncreateview (), onactivitycreated ()
- The biggest difference is that the activity is automatically in the stack, and fragment needs to explicitly declare
In the resume phase of the host activity, the fragment can be freely added/removed
Fragments | Android Developer