Fragment,fragmentmanager, Fragmenttransaction detailed

Source: Internet
Author: User
Tags commit gettext static class stub xmlns

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.

@Override public
	View Oncreateview (layoutinflater inflater, ViewGroup container,
			Bundle savedinstancestate) {
		//TODO auto-generated method stub
		View 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:cont Ext= ". Mainactivity "android:orientation=" horizontal "> <framelayout android:id=" @+id/fl "Android 
	
	 : layout_weight= "1" android:layout_width= "0DP" android:layout_height= "Match_parent" ></FrameLayout> <linearlayout android:layout_width= "wrap_content" android:layout_height= "Match_parent" and roid:orientation= "vertical" > <button android:layout_width= "Wrap_content" a
            ndroid:layout_height= "Wrap_content" android:text= "fragment01" android:onclick= "Click1" /> <button android:layout_width= "wrap_content" android:layout_height= "wrap_content
"Android:text=" fragment02 "            android:onclick= "Click2"/> <button android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" android:text= "fragment03" android:onclick= "click 3 "/> </LinearLayout> </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.

@Override public
	View Oncreateview (layoutinflater inflater, ViewGroup container,
			Bundle savedinstancestate) {
		//TODO auto-generated method stub
		View v = inflater.inflate (r.layout.fragment01, null);
		
		Final EditText et = (EditText) V.findviewbyid (r.id.et);
		Button BT = (button) V.findviewbyid (R.ID.BT);
		Bt.setonclicklistener (New Onclicklistener () {
			
			@Override public
			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 ");
       }
   }
   ...
}

If the activity does not implement that interface, fragment throws a ClassCastException exception. If successful, the Mlistener member variable holds the instance of Onarticleselectedlistener. Fragmenta can then invoke the Mlistener method to share the event with the activity. For example, if Fragmenta is a listfragment, each time you select an item in the list, the Onlistitemclick () method of Fragmenta is called, and onarticleselected () is called in this method to be associated with the Activi Ty shared 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 exist in the activity

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

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

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. In view of this, when a fragment is removed, if Addtobackstack () is called, then fragment is 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 used fragmenttransaction show or hide to achieve, ft.show (fragment); Ft.hide (fragment);









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.