Android Fragment Depth Resolution

Source: Internet
Author: User
<span id="Label3"></p><p><p><strong>1, the production and introduction of fragment</strong></p></p><p><p><strong><br></strong>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 one, modify the layout to adapt to what super large Screen. Can't you do an app that adapts to both mobile and tablet? The answer is, of course, that Fragment.fragment's original intention was to solve the Problem.</p></p><p><p>You can think of fragment as part of the activity interface, even the activity interface is composed of completely different fragment, and the more handsome is fragment has its own declaration cycle and receive, handle the User's events, This eliminates the need to write a bunch of event, control code in an Activity. More importantly, you can dynamically add, replace, remove a Fragment.</p></p><p><p><strong>2. Fragment life cycle</strong></p></p><p><p>Fragment must be dependent on activity, so the life cycle of activity can directly affect the fragment life Cycle. This picture of the official website is a good illustration of the relationship between two people:</p></p><p><p>  </p></p><p><p>You can see that fragment has several additional life-cycle callback functions than the Activity:</p></p><p><p>Onattach (Activity); <strong>//called when activity is associated with fragment</strong></p></p><p><p>Oncreateview (layoutinflater,viewgroup,bundle); <strong>//create A view of the fragment</strong></p></p><p><p>Onactivitycreate (bundle); <strong>OnCreate () When the activity is returned, or when the method returns</strong></p></p><p><p>Ondestoryview (); <strong>//corresponds to oncreateview, called when change fragment is removed</strong></p></p><p><p>Ondetach (); <strong>//corresponds to Onattach (), called when Fragment association with activity is canceled</strong></p></p><p><p>Note: In addition to oncreateview, all other methods if you rewrite, you must call the parent class for the implementation of the METHOD.</p></p><p><p><strong>3, static use of fragment</strong></p></p><p><p>next, is the time to practice, to pay attention to, began to write code ~ ~ ~ ~</p></p><p><p>This is the simplest way to use fragment, the fragment as a normal control, directly written in the activity of the layout file, with the layout file call Fragment.</p></p><p><p>Steps:</p></p><p><p>1, inherit fragment, rewrite Oncreateview decide fragment Layout.</p></p><p><p>2. Declare this fragment in the activity as if it were a normal view.</p></p><p><p>Here's An example (i use two fragment as the activity layout, a fragment for the title layout, and a fragment for the content layout).</p></p><p><p>Titlefragment's Layout file, As we can see here, we can do a separate layout for each fragment:</p></p><pre><pre><?xml version= "1.0" encoding= "utf-8"? ><relativelayout xmlns:android= "http://schemas.android.com/apk/res/ Android " android:layout_width=" fill_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=" fill_parent " android:layout_centervertical=" true " 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></pre></pre><p><p>The Titlefragment.java file, where we can see that there are separate initialization spaces in each fragment and handle events like buttons, reduces the burden on the activity, and there is no need to write a big push to initialize the control and event response code, so It makes our code look more concise, and the readability is greatly improved.</p></p><pre><pre>public class Titlefragment extends Fragment { private ImageButton mbutton; @SuppressLint ("newapi") @Override public View oncreateview (layoutinflater inflater, viewgroup container, Bundle Savedinstancestate) { View view = inflater.inflate (r.layout.title_fragment, container, false); Mbutton = (ImageButton) View.findviewbyid (r.id.id_title_left_btn); Mbutton.setonclicklistener (new onclicklistener () { @Override public void OnClick (View v) { Toast.maketext (getactivity (), "i am an ImageButton in titlefragment!" ", toast.length_short). show (); } }); return view;} }</pre></pre><p><p>And the contentfragment layout file Content_fragment.xml</p></p><pre><pre><?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></pre></pre><p><p>and the Contentfragment.java File.</p></p><pre><pre>public class Contentfragment extends Fragment { @Override public View Oncreateview (layoutinflater inflater, ViewGroup container, Bundle Savedinstancestate) { return inflater.inflate (r.layout.content_fragment, container,false);} }</pre></pre><p><p>Here's The main activity and his layout file.</p></p><pre><pre>Mainactivity.java file</pre></pre><pre><pre>public class Mainactivity extends Activity { @Override protected void OnCreate (Bundle Savedinstancestate) { super.oncreate (savedinstancestate); Requestwindowfeature (window.feature_no_title); Setcontentview (r.layout.activity_main); }}</pre></pre><p><p>Activity_main.xml file, as we can see here, we use the fragment as a normal control in an XML file.</p></p><pre><pre><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 " tools:context= "com.example.staticfragment.MainActivity" > <fragment android:name= " Com.example.staticfragment.TitleFragment " android:id=" @+id/title " android:layout_height=" 45dp " Android:layout_width= "match_parent"/> <fragment android:layout_below= "@id/title" android: Name= "com.example.staticfragment.ContentFragment" android:id= "@+id/content" android:layout_height= " Fill_parent " android:layout_width=" fill_parent "/></relativelayout></pre></pre><p><p>The results are as follows:</p></p><p><p></p></p><p><p><strong>4, the use of dynamic fragment</strong></p></p><p><p>The simplest way to use fragment has been demonstrated below to share how to dynamically add, update, and delete Fragment.</p></p><p><p>First of all, the mainactivity layout file activity_main.xml, The file layout file above the top is a titlefragment, is a statically declared Fragment.</p></p><p><p>The middle is also a fragment, but this fragment is used Dynamically.</p></p><p><p>The bottom is four buttons. Include the external layout file in the Include Tag.</p></p><pre><pre> <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 "> <frag ment android:id= "@+id/id_fragment_title" android:name= "com.example.dynamicfragment.TitleFragment" and Roid:layout_width= "fill_parent" android:layout_height= "45dp"/> <include android:id= "@+id/id_ly_bot Tombar "android:layout_width=" fill_parent "android:layout_height=" 55DP "android:layout_alignparentbot tom= "true" layout= "@layout/bottombar"/> <framelayout android:id= "@+id/id_content" android:l Ayout_width= "fill_parent" android:layout_height= "fill_parent" android:layout_above= "@id/id_ly_bottombar" android:layout_below= "@id/id_fragment_title"/></relativelayout> </pre></pre><p><p>Then there is the Mainactivity.java File. It is also the most important code file in our demo, the first is to load the above layout file through Setcontentview (). then it is through Setdefaultfragment (); the default contentfragment is dynamically loaded IN. The next step is to dynamically switch the fragment by the four buttons we've prevented at the Bottom. That's Why fragment is so Hot. ~ ~ ~ ^^</p></p><span class="cnblogs_code_copy">public <span class="cnblogs_code_copy">class Mainactivity extends Actionbaractivity implements Onclicklistener {</span></span><pre><em id="__mceDel"> Private ImageButton mtabweixin; Private ImageButton mtabfriend; Private ImageButton mtabdiscover; Private ImageButton mtabme; Private Contentfragment mweixinfragment; Private Friendfragment mfriendfragment; @Override protected void onCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Requestwindowfeature (window.feature_no_title); Setcontentview (r.layout.activity_main); Initview (); } public void Initview () {//initialize control and declare event mtabweixin = (ImageButton) Findviewbyid (r.id.weixin); Mtabfriend = (ImageButton) Findviewbyid (r.id.friend); Mtabweixin.setonclicklistener (this); Mtabfriend.setonclicklistener (this); Set the default fragment Setdefaultfragment (); } @SuppressLint ("newapi") private void setdefaultfragment () {fragmentmanager manager = Getfragmentmanager (); Fragmenttransaction transaction = Manager.begintransaction (); Mweixinfragment = new COntentfragment (); Transaction.replace (r.id.id_content, mweixinfragment); Transaction.commit (); } @SuppressLint ("newapi") @Override public void OnClick (View V) {fragmentmanager fm = Getfragmentmanager ( ); Open fragment transaction Fragmenttransaction transaction = Fm.begintransaction (); Switch (v.getid ()) {case r.id.weixin:if (mweixinfragment = = Null) {mweixinfragment = n EW contentfragment (); }//use the current fragment layout instead of the Id_content control Transaction.replace (r.id.id_content, mweixinfragment); Break Case R.id.friend:if (mfriendfragment = = Null) {mfriendfragment = new Friendfragment (); } transaction.replace (r.id.id_content, mfriendfragment); Break }//transaction.addtobackstack (); Transaction Submission Transaction.commit (); }}</em></pre><p><p>From the above code, we can see that we can use Fragmentmanager to fragment dynamic loading, the use of the Replace method here ~ ~ ~ The next section we will describe in detail the Fragmentmanager common API .... ^^</p></p><p><p>Note: If you use a android3.0 version, you need to introduce the V4 package, then the activity inherits fragmentactivity, and the Fragmentmanager object is obtained through Getsupportfragmentmanager () , however, It is recommended to change the Menifest file Uses-sdk minsdkversion and targetsdkversion to more than 11, so that you do not have to introduce V4 Package.</p></p><p><p>In the middle of the code there are two dynamically loaded fragment, this and static use Ragment declaration Way is the same, write an inheritance fragment class, and then set the corresponding layout, due to the time of the relationship, I only wrote two fragment here, Now paste these two code pages:</p></p><p><p>The first fragment and his corresponding layout file:</p></p><pre><pre>public class Contentfragment extends Fragment { @Override public View Oncreateview (layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) { return inflater.inflate (r.layout.fragment_content, container, false); } }</pre></pre><pre><pre><?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=" Weixin " android:textsize=" 20sp " android: textstyle= "bold"/> </LinearLayout> </pre></pre><p><p>The second fragment and his corresponding layout file:</p></p><pre><pre>public class Friendfragment<span style="line-height: 1.5;">extends</span><span style="line-height: 1.5;"> Fragment {</span></pre></pre><pre><pre> @Override public View oncreateview (layoutinflater inflater, viewgroup container, Bundle savedinstancestate { return inflater.inflate (r.layout.fragment_friend, container, false); } }</pre></pre><pre><pre><?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=" friend " android:textsize=" 20sp " android: textstyle= "bold"/> </LinearLayout> </pre></pre><p><p>ok, now the basic code has, we put the demo running diagram to share it for you (note: time reasons, not pay attention to the layout and image beautification, just the implementation of the function), which is clicked on the following first and second button, Thus realized the middle with a fragment dynamic loading of these two fragment display.</p></p><p><p></p></p><p><p>Ps: for the sake of brevity of the code, do not add the click Change of the button or something, the main explanation function ~ ~ ~</p></p><p><p></p></p><p><p><strong>5. Fragment Common Api:</strong></p></p><p><p>Fragment commonly used in three classes:</p></p><p><p>Android.app.Fragment is primarily used to define Fragment</p></p><p><p>Android.app.FragmentManager is primarily used to operate in activity fragment</p></p><p><p>Android.app.FragmentTransaction to ensure that some of the column fragment operation of the atom, familiar with the word business, you will understand ~</p></p><p><p><strong>a, the way to obtain fragmentmanage:</strong></p></p><p><p>Getfragmentmanager ()//v4, Getsupportfragmentmanager</p></p><p><p><strong>b, The main operation is the method of Fragmenttransaction</strong></p></p><p><p>Fragmenttransaction transaction = fm.bengintransatcion ();//open a transaction</p></p><p><p><strong>Transaction.add ()</strong></p></p><p><p>Add a fragment to the activity</p></p><p><p><strong>Transaction.remove ()</strong></p></p><p><p>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.</p></p><p><p><strong>Transaction.replace ()</strong></p></p><p><p>Replace the current with another fragment, which is actually the fit of remove () and then add () ~</p></p><p><p><strong>Transaction.hide ()</strong></p></p><p><p>Hides the current fragment, is only set to invisible, and does not destroy</p></p><p><p><strong>Transaction.show ()</strong></p></p><p><p>Show previously hidden fragment</p></p><p><p><strong>Detach ()</strong></p></p><p><p>Separating this fragment from activity destroys its layout, but does not destroy the instance</p></p><p><p><strong>Attach ()</strong></p></p><p><p>fragment, which is detached from the activity, is re-associated to the activity and re-created with its view hierarchy</p></p><p><p>Transatcion.commit ()//commit a transaction</p></p><p><p>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 ().</p></p><p><p>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.</p></p><p><p>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.</p></p><p><p><strong>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.</strong></p></p><p><p><strong>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.</strong></p></p><p><p><strong>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.</strong></p></p><p><p>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.</p></p><p><p>Android Fragment Depth Resolution</p></p></span>

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.