Fragment Analysis of Android learning

Source: Internet
Author: User
<span id="Label3"></p><strong><strong>1. Definition</strong></strong>Fragment Chinese interpretation is the meaning of fragmentation, mainly used on Large-screen devices, such as tablets, to support a more dynamic and flexible UI DESIGN. Fragment is equivalent to a modular and reusable component in your application, 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.<strong><strong>2. Features</strong></strong>(1) fragment may appear as part of the activity interface;<br>(2) multiple fragment can occur simultaneously in one activity, and one fragment can be used in multiple activity;<br>(3) during activity operation, the fragment can be added, removed or replaced;<br>(4) fragment can respond to their input events and have their own life cycles, which are affected by the life cycle of the host Activity.<strong><strong>3. Life cycle</strong></strong>Fragment must be dependent on activity, so the life cycle of activity can directly affect the fragment life Cycle.<strong><strong></strong></strong>The methods involved in the life cycle are as shown, and the specific trigger conditions are described below. <ul> <ul> <li>Onattach () <ul> <li>This method is called back when fragment is added to the activity, and is invoked only once;</li> </ul></li> <li>OnCreate () <ul> <li>A callback is called when the fragment is created, only once;</li> </ul></li> <li>Onactivitycreated () <ul> <li>Called when the activity on which the fragment is started is completed;</li> </ul></li> <li>Oncreateview () <ul> <li>The method is recalled each time it is created to draw the fragment view component;</li> </ul></li> <li>OnStart () <ul> <li>Start fragment</li> </ul></li> <li>Onresume () <ul> <li>The callback is called when the fragment is restored, and the Onresume () method is called after calling the OnStart () method;</li> </ul></li> <li>OnStop () <ul> <li>Stop fragment</li> </ul></li> <li>Ondestroyview () <ul> <li>Called when destroying the view component contained by fragment</li> </ul></li> <li>OnDestroy () <ul> <li>Callback when destroying fragment</li> </ul></li> <li>Ondetach () <ul> <li>The method is called back when fragment is removed from the activity, and this method calls only once</li> </ul></li> </ul> </ul><p align="left"><p align="left"><strong>4. Static Loading</strong></p></p><p align="left"><p align="left">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 align="left"><p align="left">(1) new fragment, rewrite Oncreateview decide fragment layout</p></p><pre><pre> @Override public View oncreateview (layoutinflater inflater, viewgroup container, Bundle Savedinstancestate) { //inflate the layout for this fragment return inflater.inflate (r.layout.fragment_static, container, false); c5/>}</pre></pre>(2) manually adding fragment to the host activity, use it as a normal control in an XML file. The Name property fills in the fragment package path, and the activity obtains fragment through Findfragmentbyid () or Findfragmentbytag ().<pre><pre><fragment android:name= "ant.snail.com.fragmentactapp.StaticFragment" android:layout_width= "wrap_ Content " android:layout_height=" wrap_content " android:tag=" Newfrag "/></pre></pre><p><p>This allows the fragment to be seen in the host Activity.</p></p><p align="left"><p align="left"><strong>5. Dynamic Loading</strong></p></p><p align="left"><p align="left">The above static loading is the most basic method, the following parsing the principle of dynamic loading.</p></p><p align="left"><p align="left">(1) <strong>principle</strong></p></p><p align="left"><p align="left"><strong>  </strong>Dynamic loading, as the name implies, is to load fragment in the activity in the form of Code.</p></p><p align="left"><p align="left">By writing code to add fragment to an activity layout, you need to use fragment transaction (fragmenttransaction), which is a bit like a database Transaction.</p></p> <ol> <ol> <li>Each set of changes submitted to the activity is referred to as a transaction, depending on the User's interaction, adding, removing, replacing, and performing other actions on the fragment;</li> <li>Each transaction performs a set of changes at the same time, and you can set all the changes you want to perform in a transaction, including add (), remove (), replace (), and then commit to the activity and finally the commit () method;</li> <li>If the user is allowed to return to the previous fragment state by pressing the back key, the Addtobackstack () method can be added before calling commit ().</li> </ol> </ol><p align="left"><p align="left">(2) <strong>Concrete Realization</strong></p></p><p align="left"><p align="left">By creating a new two fragment and adding ImageView to the two fragment layout, the two fragment are dynamically toggled in the host activity, enabling a free transition of the Image. The code structure is as Shown.</p></p><p align="left"><p align="left"></p></p><p align="left"><p align="left"></p></p><p><p>New fragment (image1fragment,image2fragment), and added two layout files (fragment_image1,fragment_image2), some of which are as Follows:</p></p><p><p>Image1fragmet code:</p></p><span class="cnblogs_code_copy"><span class="cnblogs_code_copy"></span></span><pre><pre> @Override public View oncreateview (layoutinflater inflater, viewgroup container, Bundle Savedinstancestate) { //get Fragment's View View view=inflater.inflate (r.layout.fragment_image1,container,false);<br> return view; }</pre></pre><span class="cnblogs_code_copy"><span class="cnblogs_code_copy"></span></span><p><p>The Fragment_image1.xml file code is as Follows:</p></p><span class="cnblogs_code_copy"><span class="cnblogs_code_copy"></span></span><pre><linearlayout 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 "android:orien tation= "vertical" android:gravity= "center_horizontal" tools:context= "ant.snail.com.fragmentactapp.Image1Fragment "> <!--todo:update Blank fragment layout--<linearlayout android:orientation=" Horizontal " Android:layout_width= "match_parent" android:layout_height= "wrap_content" android:layout_gravity= "cen Ter_horizontal "android:gravity=" Center "> <textview android:id=" @+id/text1 " Android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:text= "i am Jin Rabbit 1"/ > <button android:layout_marginleft= "10dp" android:layout_width= "wrap_content" android:layout_height= "wrap_content"android:text= "pass data to main window" android:id= "@+id/btfr1"/> </LinearLayout> <imageview android: Layout_width= "wrap_content" android:layout_height= "wrap_content" android:id= "@+id/imageview1" Android : src= "@drawable/jin1"/></linearlayout></pre><span class="cnblogs_code_copy"><span class="cnblogs_code_copy"></span></span><p><p>The code of the host mainactivity is as follows, the fragmenttransaction is obtained through fragmentmanager, then the switch between the two fragment is realized through the replace () method, and finally the commit () method is implemented:</p></p><span class="cnblogs_code_copy"><span class="cnblogs_code_copy"></span></span><pre> protected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); Gets the Two-button view bt1= (button) Findviewbyid (r.id.bt1); bt2= (Button) Findviewbyid (r.id.bt2); Bt1.setonclicklistener (new view.onclicklistener () {@Override public void OnClick (View V) { The main activity dynamically loads fragment Fragmentmanager Fragmentmanager=getfragmentmanager (); Handling Fragment Transactions Fragmenttransaction begintransaction=fragmentmanager.begintransaction (); Get image1fragment instance image1fragment image1fragment=image1fragment.newinstance ("activity passes pictures 1 through fragment"); Replacement Operation Begintransaction.replace (r.id.imagelayout,image1fragment); Allows the user to return to the previous fragment state Begintransaction.addtobackstack (null) by pressing the back button; Begintransaction.commit (); } }); Bt2.setonclicklistener (new view.onclicklistener () {@Override public void OnClick (View V) { The main activity dynamically loads fragment Fragmentmanager Fragmentmanager=getfragmentmanager (); Handling Fragment Transactions Fragmenttransaction begintransaction=fragmentmanager.begintransaction (); Get image1fragment instance image2fragment image2fragment=image2fragment.newinstance ("activity passes pictures 2 through fragment"); Replacement Operation Begintransaction.replace (r.id.imagelayout,image2fragment); Allows the user to return to the previous fragment state Begintransaction.addtobackstack (null) by pressing the back button; Begintransaction.commit (); } }); }</pre><span class="cnblogs_code_copy"><span class="cnblogs_code_copy"></span></span><p><p>The Newinstance method is an instance method implemented in fragment that instantiates the fragment and passes the data in the activity to fragment through the pass of the parameter param1. Data is passed from activity to fragment through Setarguments () and getarguments (), as shown in.</p></p><span class="cnblogs_code_copy"><span class="cnblogs_code_copy"></span></span><pre><pre>public static image1fragment newinstance (String param1) { image1fragment fragment = new Image1fragment (); Create bundle packets in activity and call Fragment's setarguments (bundle Bundle) method Bundle args = new bundle (); Args.putstring (arg_param1, param1); Fragment.setarguments (args); return fragment; }</pre></pre><span class="cnblogs_code_copy"><span class="cnblogs_code_copy"></span></span><span class="cnblogs_code_copy"><span class="cnblogs_code_copy"></span></span><pre><pre> @Override public void onCreate (Bundle Savedinstancestate) { super.oncreate (savedinstancestate); If (getarguments () = Null) { //in fragment through getarguments (). getString () Gets the value of the activity coming mParam1 = getarguments ( ). getString (arg_param1); } }</pre></pre><span class="cnblogs_code_copy"><span class="cnblogs_code_copy"></span></span><p align="left"><p align="left">6.<strong>Fragment and Activity communication</strong></p></p> <ul> <ul> <li><strong>Fragment call the data in the activity</strong></li> </ul> </ul>Create bundle packets in activity and invoke Fragment's setarguments (bundle Bundle) method, as described in the code Above. <ul> <ul> <li><strong>Activity calls the data in fragment</strong></li> </ul> </ul>Define an internal callback interface in fragment that enables the activity that contains the fragment to implement the callback interface so that fragment can invoke the callback method to pass the data to the Activity. The following is the main implementation of the activity called Fragment Data. First define an internal callback interface in Fragment:<pre><pre> public interface Onfragmentinteractionlistener {public void onfragmentinteraction (String uri); </pre></pre><p><p>Convert activity to Onfragmentinteractionlistener interface in Fragment's Onattach () method:</p></p><span class="cnblogs_code_copy"><span class="cnblogs_code_copy"></span></span><pre><pre>@Override public void Onattach (activity activity) { super.onattach (activity); Try { mlistener = (onfragmentinteractionlistener) activity; } catch (classcastexception e) { throw new ClassCastException (activity.tostring () + "must implement onfragmentinteractionlistener"); } }</pre></pre><pre><pre>Private Onfragmentinteractionlistener mlistener;</pre></pre><pre><pre>If (mlistener! = Null) {<br> Mlistener.onfragmentinteraction ("value to be passed to activity");</pre></pre><pre><pre></pre></pre><span class="cnblogs_code_copy"><span class="cnblogs_code_copy"></span></span><p><p>The host activity needs to implement this interface and override the Onfragmentinteraction (String Uri) method, which enables the delivery of data from fragment to Activity:</p></p><span class="cnblogs_code_copy"><span class="cnblogs_code_copy"></span></span><pre><pre>public class Mainactivity extends actionbaractivity implements Image1fragment.onfragmentinteractionlistener</pre></pre><pre><pre>@Override<br>public void Onfragmentinteraction (String Uri) {<br> TextView tv= (TextView) Findviewbyid (r.id.tt);<br> Tv.settext (uri);<br>}</pre></pre><span class="cnblogs_code_copy"><span class="cnblogs_code_copy"></span></span><p><p><strong>7. Effects</strong></p></p><p><p></p></p><p><p>Fragment Analysis of Android learning</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.