Fragment,fragmentmanager, Fragmenttransaction detailed

Source: Internet
Author: User

The fragment is a new component introduced in 3.0, and is used frequently in projects where the V4 package is fragment to be backwards compatible before 3.0.

Let's say 3.0 fragment usage.

Among them, fragment's life cycle is not much to say, first constructs the Fragment view object.

@Overridepublic View Oncreateview (layoutinflater inflater, ViewGroup container,bundle savedinstancestate) {//TODO Auto-generated method Stubview v = inflater.inflate (r.layout.fragment02, null); return v;}

The target fragment is then displayed in the activity.

@Override    protected void onCreate (Bundle savedinstancestate) {        super.oncreate (savedinstancestate);        Setcontentview (r.layout.activity_main);                FG3 = new Fragment03 ();    Get fragment manager    Fragmentmanager FM = Getfragmentmanager ();    Open transaction    fragmenttransaction ft = fm.begintransaction ();    Display the content to the frame layout    ft.replace (R.ID.FL, FG3);    Submit    Ft.commit ();    }


It is important to note that fragment can only replace framelayout in the activity.

<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 "Tools:context =". Mainactivity "android:orientation=" horizontal "> <framelayout android:id=" @+id/fl "Android:layout_we ight= "1" android:layout_width= "0DP" android:layout_height= "match_parent" ></FrameLayout> <linearlayou T android:layout_width= "wrap_content" android:layout_height= "match_parent" android:orientation= "Verti Cal "> <button android:layout_width=" wrap_content "android:layout_height=" Wrap_             Content "android:text=" fragment01 "android:onclick=" Click1 "/> <button Android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:text= "Fragme   nt02 "android:onclick=" Click2 "         /> <button android:layout_width= "wrap_content" android:layout_height= "Wrap_co Ntent "android:text=" fragment03 "android:onclick=" Click3 "/> </linearlayout>& Lt;/linearlayout>


Then we say fragment's backwards compatibility mode:

First of all, we must first import the V4 package that comes with the system.

Package Com.itheima.supportfragment;import Android.os.bundle;import Android.app.activity;import Android.support.v4.app.fragmentactivity;import Android.support.v4.app.fragmentmanager;import Android.support.v4.app.fragmenttransaction;import Android.view.menu;import Android.view.view;public Class Mainactivity extends Fragmentactivity {    private Fragment03 fg3; @Override    protected void OnCreate (Bundle Savedinstancestate) {        super.oncreate (savedinstancestate);        Setcontentview (r.layout.activity_main);                FG3 = new Fragment03 ();    Get fragment manager    Fragmentmanager FM = Getsupportfragmentmanager ();    Open transaction    fragmenttransaction ft = fm.begintransaction ();    Display the content to the frame layout    ft.replace (R.ID.FL, FG3);    Submit    Ft.commit ();    }}

The same as the previous use method, is to replace the framelayout layout in the activity.

Finally, the transfer of data between activity and fragment.

@Overridepublic View Oncreateview (layoutinflater inflater, ViewGroup container,bundle savedinstancestate) {//TODO Auto-generated method Stubview v = inflater.inflate (r.layout.fragment01, NULL); final EditText et = (EditText) v.findviewb Yid (R.id.et); Button BT = (button) V.findviewbyid (R.ID.BT), Bt.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) {String text = Et.gettext (). toString ();//Pass data to activity ((mainactivity) getactivity ()). SetText (text);}); return v;}
Fragment directly calls Getactivity () to get the activity object when the data is passed to the activity.

public void Click4 (View v) {        String text = Et_main.gettext (). toString ();        Pass Data    fg3.settext (text);    }
When the activity passes data to fragment, the new one fragment.

However, it is best to use callback interface to transfer data between general fragment and activity. The advantage of this is that it facilitates the reusability of fragment.

public static class Fragmenta extends listfragment{...   Container Activity must implement this interface public   interface onarticleselectedlistener{public       void onarticleselected (Uri Articleuri);   }   ...}
public static class Fragmenta extends listfragment{   onarticleselectedlistener Mlistener;   ...   @Override public   void Onattach (activity activity) {       Super.onattach (activity);       try{           Mlistener = (onarticleselectedlistener) activity;       } catch (ClassCastException e) {           throw new ClassCastException (activity.tostring () + "must implement Onarticleselectedlistener ");       }   }   ...}

ifActivitywithout implementing that interface,Fragmentthrownclasscastexceptionexception. If it succeeds,Mlistenermember Variable SaveOnarticleselectedlistenerthe instance. SoFragmentaYou can callMlistenerthe method toActivityshared events. For example, ifFragmentais alistfragment, each time you select an item in the list, it calls theFragmentaof theOnlistitemclick ()method, which is called in this methodonarticleselected ()come withActivityshared events, as follows:

public static class Fragmenta extends listfragment{   onarticleselectedlistener Mlistener;   ...   @Override public   void Onlistitemclick (ListView l,view v,int position,long id) {       //append the clicked item ' s row ID With the content provider Uri       URI Noteuri =contenturis.withappendedid (articlecolumns.content_uri,id);       Send the event and Uri to the host activity       mlistener.onarticleselected (Noteuri);   }   ...}


Fragmentmanager is used to manage the fragment, using the activity of the Getfragmentmanager () to obtain its instance.

There are a few things fragmentmanager can do:

1. Use Findfragmentbyid () (fragment for providing a UI in activity layout) or Findfragmentbytag () (for fragment with or without UI) get the fragment that exists in the activity

2. Eject the fragment from the background stack, using Popbackstack ()

3. Register a listener that listens for background stack changes using Addonbackstackchangelist ener ().

Fragmenttransaction is the operation of adding, replacing, removing, and so on fragment.
 when using Add (), replace (), remove () can dynamically add a label to each fragment, the next convenient fragmentmanager through the tag tag to find. Finally remember Ft.commit ();   
When executing a transaction that removes fragment, if Addtobackstack () is not called, then when the transaction commits, that fragment is destroyed and the user cannot navigate back to it. Because of this, when you remove a fragment, if you call the Addtobackstack (), then fragment will be stopped, and if the user navigates back, it will be restored.////I think is important, the above words can be understood, remove after adding to the stack. Press to return or return to the previous fragment.  fragment display and hide can be achieved with fragmenttransaction show or hide,  ft.show (fragment); Ft.hide (fragment);









Fragment,fragmentmanager, Fragmenttransaction detailed

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.