Reprint please indicate source: http://blog.csdn.net/lmj623565791/article/details/37970961
Since fragment appeared, there has been a period of time, I feel that we can talk about anything with fragment talk on the relationship, do anything to ask fragment can realize not ~ ~ ~ Haha, is not a bit too ~ ~ ~
This blog seeks to show you how fragment, what is the fragment,fragment life cycle, how to use static and dynamic fragment,fragment fallback stack, fragment transaction, and some special uses of fragment, For example: What is the use of fragment without layouts? How does fragment interact with activity? Fragment how do I create a dialog box? Fragment how to integrate with Actionbar and so on.
1, the production and introduction of fragment
Android runs on a wide variety of devices, with small screen phones, oversized flat panels and even TVs. For the screen size gap, in many cases, the first to develop a set of apps for the mobile phone, and then copy, modify the layout to adapt to the plate God horse super large screen. Can't it be that an app can adapt to both the phone and the tablet, of course, must have. The appearance of fragment is to solve such problems. You can think of fragment as a part of an activity interface, even the activity of the interface can be completely different fragment composition, more handsome is fragment have their own life cycle and receive, handle the user's events, This eliminates the need to write a bunch of control's event-handling code in the activity. More importantly, you can dynamically add, replace, and remove a fragment.
2. Fragment Life cycle
Fragment must be dependent and activity, so the life cycle of activity can directly affect the life cycle of fragment. This map of the official website is a good illustration of the relationship between the two life cycles:
You can see that fragment has several additional life-cycle callback methods than the activity:
Onattach (Activity)
Called when the fragment is associated with an activity.
Oncreateview (Layoutinflater, Viewgroup,bundle)
Create a view of the fragment
Onactivitycreated (Bundle)
Called when the activity's OnCreate method returns
Ondestoryview ()
and Oncreateview want to correspond, when the fragment view is removed when the call
Ondetach ()
Corresponds to Onattach, called when the fragment associated with the activity is canceled
Note: In addition to Oncreateview, all other methods if you rewrite, you must call the parent class for the implementation of the method,
3, static use of fragment
Hey, finally to the use of the moment ~ ~
This is the simplest way to use fragment, fragment as a normal control, written directly in the activity's layout file. Steps:
1, inherit fragment, rewrite Oncreateview decide fragemnt layout
2. Declare this fragment in the activity, just as with the normal view
Here's an example (I use 2 fragment as the activity layout, a fragment for the title layout, and a fragment for the content layout):
Titlefragment Layout file:
<?xml version= "1.0" encoding= "Utf-8"? ><relativelayout xmlns:android= "http://schemas.android.com/apk/res/ Android " android:layout_width=" match_parent " android:layout_height=" 45DP " android:background=" @ Drawable/title_bar "> <imagebutton android:id=" @+id/id_title_left_btn " android:layout_width=" Wrap_content " android:layout_height=" wrap_content " android:layout_centervertical=" true " Android: layout_marginleft= "3DP" android:background= "@drawable/showleft_selector"/> <textview Android:layout_width= "Fill_parent" android:layout_height= "fill_parent" android:gravity= "center" android:text= "I am not" android:textcolor= "#fff" android:textsize= "20sp" android:textstyle= " Bold "/></relativelayout>
Titlefragment
Package Com.zhy.zhy_fragments;import Android.app.fragment;import Android.os.bundle;import Android.view.layoutinflater;import Android.view.view;import Android.view.view.onclicklistener;import Android.view.viewgroup;import Android.widget.imagebutton;import Android.widget.toast;public class TitleFragment Extends Fragment{private ImageButton mleftmenu; @Overridepublic View Oncreateview (layoutinflater inflater, ViewGroup Container,bundle savedinstancestate) {View view = Inflater.inflate (R.layout.fragment_title, container, false); Mleftmenu = (ImageButton) View.findviewbyid (R.ID.ID_TITLE_LEFT_BTN); Mleftmenu.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) {toast.maketext (getactivity (), "I am a ImageButton in Titlefragment! ", Toast.length_short). Show ();}}); return view;}}
In the same vein, there are Contentfragment's layout files:
<?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:o rientation= "vertical" > <textview android:layout_width= "fill_parent" android:layout_height= " Fill_parent " android:gravity=" center " android:text=" Using fragment Dashboard " android:textsize=" 20SP " Android:textstyle= "Bold"/></linearlayout>
Package Com.zhy.zhy_fragments;import Android.app.fragment;import Android.os.bundle;import Android.view.layoutinflater;import Android.view.view;import Android.view.viewgroup;public class ContentFragment Extends fragment{@Overridepublic View oncreateview (layoutinflater inflater, ViewGroup container,bundle Savedinstancestate) {return inflater.inflate (R.layout.fragment_content, container, false);}}
Mainactivity
Package Com.zhy.zhy_fragments;import Android.app.activity;import Android.os.bundle;import Android.view.Window; public class Mainactivity extends activity{@Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Requestwindowfeature (Window.feature_no_title); Setcontentview (R.layout.activity_main);}}
Activity's layout file:
<relativelayout 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 " > <fragment android:id= "@+id/id_fragment_title" android:name= "com.zhy.zhy_fragments. Titlefragment " android:layout_width=" fill_parent " android:layout_height=" 45DP "/> <fragment android:layout_below= "@id/id_fragment_title" android:id= "@+id/id_fragment_content" android:name = "Com.zhy.zhy_fragments." Contentfragment " android:layout_width=" fill_parent " android:layout_height=" Fill_parent "/></ Relativelayout>
is not the fragment as a normal view in the activity layout file, and then all the control of the event processing and other code by the respective fragment to deal with, instantly feel activity good clean have wood ~ ~ Code readability, Reusability and maintainability are not instantly lifted ~ ~ ~ See below:
4, the use of dynamic fragment
As shown above, the simplest way to use fragment is to describe how to dynamically add, update, and delete fragment
In order to use fragment dynamically, we modify the actvity layout file, in the middle using a framelayout, the following add four buttons ~ ~ ~ Hehe ~ ~ Not the button-!
<relativelayout 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 " > <fragment android:id= "@+id/id_fragment_title" android:name= "com.zhy.zhy_fragments. Titlefragment " android:layout_width=" fill_parent " android:layout_height=" 45DP "/> <include android:id= "@+id/id_ly_bottombar" android:layout_width= "fill_parent" android:layout_height= " 55DP " android:layout_alignparentbottom=" true " layout=" @layout/bottombar "/> <framelayout android:id= "@+id/id_content" android:layout_width= "fill_parent" android:layout_height= "Fill_ Parent " android:layout_above=" @id/id_ly_bottombar " android:layout_below=" @id/id_fragment_title "/> </RelativeLayout>
The layout of the bottom four buttons is not affixed, and then see it.
The following main activity
Package Com.zhy.zhy_fragments;import Android.app.activity;import Android.app.fragmentmanager;import Android.app.fragmenttransaction;import Android.os.bundle;import Android.view.view;import Android.view.view.onclicklistener;import Android.view.window;import Android.widget.linearlayout;public Class Mainactivity extends Activity implements Onclicklistener{private LinearLayout mtabweixin;private linearlayout Mtabfriend;private contentfragment mweixin;private friendfragment mfriend; @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Requestwindowfeature (Window.feature_no_title); Setcontentview (R.layout.activity_main);//Initialize control and declare event Mtabweixin = (linearlayout) Findviewbyid (r.id.tab_bottom_ Weixin); mtabfriend = (linearlayout) Findviewbyid (r.id.tab_bottom_friend); Mtabweixin.setonclicklistener (this); Mtabfriend.setonclicklistener (this);//Set default Fragmentsetdefaultfragment ();} private void Setdefaultfragment () {Fragmentmanager fm = Getfragmentmanager (); FragmenttRansaction transaction = Fm.begintransaction (); mweixin = new Contentfragment (); Transaction.replace (R.id.id_content, Mweixin); Transaction.commit ();} @Overridepublic void OnClick (View v) {Fragmentmanager fm = Getfragmentmanager ();//Turn on fragment transaction fragmenttransaction Transaction = fm.begintransaction (); switch (V.getid ()) {case R.id.tab_bottom_weixin:if (mweixin = = null) {mweixin = new Contentfragment ();} Use the current fragment layout instead of the Id_content control Transaction.replace (R.id.id_content, mweixin); Break;case r.id.tab_bottom_friend: if (mfriend = = null) {mfriend = new friendfragment ();} Transaction.replace (R.id.id_content, mfriend); Transaction.addtobackstack ();//Transaction commit transaction.commit ();}}
You can see that we use Fragmentmanager to dynamically load the fragment, which uses the Replace method ~ ~ The next section I will detail the Fragmentmanager common API.
Note: If you use a version below Android3.0, you need to introduce V4 's package, then the activity inherits Fragmentactivity, and then Getsupportfragmentmanager gets fragmentmanager. However, the proposed version of the Menifest file Uses-sdk minsdkversion and targetsdkversion are changed to more than 11, so there is no need to introduce V4 package.
In the middle of the code there are two sub-classes of fragment, contentfragment have seen above, friendfragment in fact similar:
Package Com.zhy.zhy_fragments;import Android.app.fragment;import Android.os.bundle;import Android.view.layoutinflater;import Android.view.view;import Android.view.viewgroup;public class FriendFragment Extends fragment{@Overridepublic View oncreateview (layoutinflater inflater, ViewGroup container,bundle Savedinstancestate) {return inflater.inflate (R.layout.fragment_friend, container, false);}}
:
Can see very good implementation of the effect, in fact, the effect of the previous blog has also appeared in the blog: Android Project tab type main interface Big summary fragment+tabpageindicator+viewpager, interested can see. PS: For the sake of brevity of the code, do not add the click Change of the button or something, the main explanation function ~ ~ ~
5, the fragment family commonly used API
Fragment commonly used in three classes:
Android.app.Fragment is primarily used to define Fragment
Android.app.FragmentManager is primarily used to operate in activity fragment
Android.app.FragmentTransaction to ensure that some of the column fragment operation of the atom, familiar with the word business, you will understand ~
A, the way to obtain Fragmentmanage:
Getfragmentmanager ()//V4, Getsupportfragmentmanager
b, the main operation is the method of Fragmenttransaction
Fragmenttransaction transaction = Fm.bengintransatcion ();//Open a transaction
Transaction.add ()
Add a fragment to the activity
Transaction.remove ()
Remove a fragment from the activity, if the removed fragment is not added to the fallback stack (which is detailed later in the fallback stack), the fragment instance will be destroyed.
Transaction.replace ()
Replace the current with another fragment, which is actually the fit of remove () and then add () ~
Transaction.hide ()
Hides the current fragment, is only set to invisible, and does not destroy
Transaction.show ()
Show previously hidden fragment
Detach ()
The view is removed from the UI, unlike remove (), where the state of the fragment is maintained by Fragmentmanager.
Attach ()
Rebuilds the view view, attaches to the UI, and displays.
Transatcion.commit ()//Commit a transaction
Note: Common fragment buddies may often encounter such an activity state inconsistency: loss this error. The main reason is that the commit method must be called before Activity.onsaveinstance ().
Above, basically is the operation fragment all way, in one transaction opens to commits can carry on the multiple addition, the removal, the substitution and so on operation.
It is worth noting that if you like to use fragment, be sure to understand these methods, which will destroy the view, which will destroy the instance, which is just hidden, so that you can better use them.
A, for example: I fill in the Fragmenta in the EditText some data, when switching to FRAGMENTB, if you want to see the data to a can also be the right for you is hide and show, that is, want to retain the user operation of the panel, you can use hide and show And, of course, don't try to make a non-null judgment on that new instance.
B, another example: I do not want to keep the user operation, you can use remove (), and then add (), or use replace () this and remove,add is the same effect.
C, remove and detach have a slight difference, without considering the fallback stack, remove destroys the entire fragment instance, and detach simply destroys its view structure, and the instance is not destroyed. So how do they choose to use it? If your current activity persists, you may prefer to use detach when you do not want to retain user action.
The above has been introduced to complete the fragment commonly used some methods, I believe that after reading, we must clearly understand the reasons for fragment, and how to use the fragment, and then according to the API explanation, also can understand, why once thought fragment will appear some disorderly seven or eight slot problem, After all, it is because the life cycle is not clear.
For space reasons, the rest of the content is left to the next article. In the next article, we will introduce:
1, how to manage fragment fallback stack
2. How fragment interacts with activity
3. Best practices for fragment interaction with activity
4. The use of fragment without views
5. Create a dialog box with fragment
6, how to integrate with Actionbar,menuitem, etc. ~ ~
Next: Android Fragment Real full parsing (next)
OK, have any questions please leave a message ~ ~
from:http://blog.csdn.net/lmj623565791/article/details/37970961
"Go" Android Fragment Real Full parse (on)