Fragment Analysis of Android learning

Source: Internet
Author: User

1. DefinitionFragment 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. 2. Features (1) fragment may appear as part of the activity interface;
(2) Multiple fragment can occur simultaneously in one activity, and one fragment can be used in multiple activity;
(3) During activity operation, the fragment can be added, removed or replaced;
(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. 3. Life cyclefragment must be dependent on activity, so the life cycle of activity can directly affect the fragment life cycle. The methods involved in the life cycle are as shown, and the specific trigger conditions are described below.
    • Onattach ()
      • This method is called back when fragment is added to the activity, and is invoked only once;
    • OnCreate ()
      • A callback is called when the fragment is created, only once;
    • Onactivitycreated ()
      • Called when the activity on which the fragment is started is completed;
    • Oncreateview ()
      • The method is recalled each time it is created to draw the Fragment view component;
    • OnStart ()
      • Start fragment
    • Onresume ()
      • The callback is called when the fragment is restored, and the Onresume () method is called after calling the OnStart () method;
    • OnStop ()
      • Stop fragment
    • Ondestroyview ()
      • Called when destroying the view component contained by fragment
    • OnDestroy ()
      • Callback when destroying fragment
    • Ondetach ()
      • The method is called back when fragment is removed from the activity, and this method calls only once

4. Static loading

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.

(1) New fragment, rewrite Oncreateview decide fragment layout

    @Override    public  View oncreateview (layoutinflater inflater, ViewGroup container,                             Bundle savedinstancestate) {        //  inflate the layout for this fragment        return false );    }
(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 ().
<fragment         android:name= "Ant.snail.com.fragmentactapp.StaticFragment"         android:layout_ Width= "Wrap_content"         android:layout_height= "Wrap_content"         android:tag= "Newfrag" />

This allows the fragment to be seen in the host activity.

5. Dynamic Loading

The above static loading is the most basic method, the following parsing the principle of dynamic loading.

(1) principle

  Dynamic loading, as the name implies, is to load fragment in the activity in the form of code.

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.

    1. 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;
    2. 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;
    3. 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 ().

(2) Concrete realization

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.

New Fragment (Image1fragment,image2fragment), and added two layout files (fragment_image1,fragment_image2), some of which are as follows:

Image1fragmet Code:

    @Override    public  View oncreateview (layoutinflater inflater, ViewGroup container,                             Bundle savedinstancestate) {        //  get fragment's view        View view=inflater.inflate (R.layout.fragment_image1,container,false);
return view; }

The Fragment_image1.xml file code is as follows:

<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:orientation= "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= "Center_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>

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:

 protected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); //get view of two buttonsbt1=(Button) Findviewbyid (R.ID.BT1); BT2=(Button) Findviewbyid (R.ID.BT2); Bt1.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {//main activity dynamic loading fragmentFragmentmanager fragmentmanager=Getfragmentmanager (); //Handling Fragment TransactionsFragmenttransaction begintransaction=fragmentmanager.begintransaction (); //Get Image1fragment InstanceImage1fragment image1fragment=image1fragment.newinstance ("activity passes pictures 1 to fragment"); //Replace OperationBegintransaction.replace (r.id.imagelayout,image1fragment); //allows the user to return to the previous fragment state by pressing the back buttonBegintransaction.addtobackstack (NULL);            Begintransaction.commit ();        }        }); Bt2.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {//main activity dynamic loading fragmentFragmentmanager fragmentmanager=Getfragmentmanager (); //Handling Fragment TransactionsFragmenttransaction begintransaction=fragmentmanager.begintransaction (); //Get Image1fragment InstanceImage2fragment image2fragment=image2fragment.newinstance ("activity passes pictures 2 to Fragment"); //Replace OperationBegintransaction.replace (r.id.imagelayout,image2fragment); //allows the user to return to the previous fragment state by pressing the back buttonBegintransaction.addtobackstack (NULL);            Begintransaction.commit ();    }        }); }

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.

 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; } 
  @Override    publicvoid  onCreate (Bundle savedinstancestate) {          Super. OnCreate (savedinstancestate);         if NULL ) {            // in Fragment by Getarguments (). GetString () Gets the value of the activity coming            mParam1 = getarguments (). getString (ARG_PARAM1);        }    }

6.Fragment and Activity communication

    • Fragment call the data in the activity
Create bundle packets in activity and invoke fragment's setarguments (Bundle bundle) method, as described in the code above.
    • Activity calls the data in fragment
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:
  Publicinterface  onfragmentinteractionlistener {public        void onfragmentinteraction (String uri);    }

Convert activity to Onfragmentinteractionlistener interface in Fragment's Onattach () method:

@Override      Public void Onattach (activity activity) {        superOnattach (activity);         Try {            = (onfragmentinteractionlistener) activity;         Catch (classcastexception e) {            thrownew  classcastexception (activity.tostring ()                    + "must implement Onfragmentinteractionlistener");        }    }
Private Onfragmentinteractionlistener Mlistener;
if (Mlistener! = null) {
Mlistener.onfragmentinteraction ("value to be passed to activity");

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:

 Public class extends Implements Image1fragment.onfragmentinteractionlistener
@Override
public void Onfragmentinteraction (String uri) {
TextView tv= (TextView) Findviewbyid (R.ID.TT);
Tv.settext (URI);
}

7. Effects

Fragment Analysis of Android learning

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.