"Reproduced" in Android development skillfully use activity and fragment

Source: Internet
Author: User

Life cycle of 1.Activity

1) A number of activities are composed of activity stacks, currently active at the top of the stack. Let's take a look at the class diagram of the various activity base classes:

When the activity class is defined, when the activity is instantiated and when the method it contains is invoked, these are not determined by the developer, and should be determined by the Android system.

Let's look at the life cycle of the activity:

Usage of 2.Activity

1) Start and close activity

New Intent (mainactivity.  This, twoactivity. class); ///Requestcode: The Request code //startactivityforresult method initiates activity with the specified request code and obtains the returned result by overriding the Onactivityresult method. //close Activityfinish (); finishactivity (int requestcode);  The Finishactivity method ends the activity that starts with the Startactivityforresult method. 

2) Start other activity and return results

Current Activity rewrite onactivityresult (int requestcode, int resultcode, Intent Intent)
Requestcode: The request code (indicating which request the method was triggered from)
The result code returned by the Resultcode:activity (indicates which new activity the returned data is from)
The activated activity needs to call the Setresult () method to set the processing result.

Instance:

Overriding the Onactivityresult method in the current activity

PublicClassMainactivityExtendsActivity {Button bn;@OverridePublicvoidOnCreate(Bundle savedinstancestate) {Super.oncreate (savedinstancestate); Setcontentview (R.layout.main);Get the components on the interface ...Bind Event Listener Bn.setonclicklistener (New Onclicklistener () {@OverridePublicvoidOnClick(View view) {Intent Intent =New Intent (mainactivity.this, twoactivity.class); Startactivityforresult (Intent,0); //0 is the request code to identify the request}); }  @Override public void onactivityresult ( int Requestcode, int ResultCode, Intent Intent) {//processing specific results if (Requestcode = 0 && ResultCode = = 0) {//Remove intent data Bundle from extras Intent.getextras (); //out the data in the bundle String result = data.getstring ( "test"); Toast.maketext (Getapplicationcontext (), result, 0). Show ();}}     

Then call the Setresult () method in the twoactivity that was started to set the processing result

Gets the activity corresponding to intentintent intent = getintent () Intent.putextra ("test") before initiating the activity;  Set the result code for the selectactivity and set the activityselectcityactivity to be returned after the end. This.setresult (0, intent);  End Twoactivitytwoactivity. this.finish ();     
3. Use bundles to exchange data between activity

Intent provides a number of overloaded methods to "carry" additional data, as follows:

Intent the Packet Intent.putextras (//Remove the packet that iscarried in the intent Intent.getxxxextras (//Remove the specified type of data from the intent by pressing key) 

The bundle in the above method is a simple data carrying packet, intent mainly through the bundle object to carry the data, the bundle contains several methods to access the data:

First create a Bundle object Bundle.putxxx (//put data into the bundle bundle.putserializable (/// Put a serializable object into the bundle (that is, implement the Java.io.Serializable Interface) bundle.getxxx (//Remove the data from the bundle bundle.getserializable (// Extracting a serializable object from the bundle   
Four load modes for 4.Activity

When you configure activity in Androidmanifest.xml, you can specify that the Android:launchmode property is used to configure the load mode for the activity, which supports 4 property values:
Standard: standardized mode;
Singletop: Stack top single case mode;
Singletask: In-stack singleton mode (if the target activity already exists but not at the top of the stack, the system moves all the activity on top of the activity out of the task stack so that the target activity is transferred to the top of the stack);
SingleInstance: Global Singleton mode (the newly created activity will be put into a new stack, a stack contains only one activity, and if the target activity already exists, the system will transfer the activity's task to the foreground display).

Life cycle of 5.Fragment

Fragment is Androi . The new api,fragment introduced by D3.0 represents the Activity sub-module (activity fragment), fragment must be embedded in the activity, and the fragment life cycle is controlled by the life cycle of the activity in which it resides.

Fragment can call the Getactivity () method to obtain its activity;
Activity can call Fragmentmanager's Findfragmentbyid () or Findfragmentbytag () method to obtain fragment;
You can invoke the Add (), remove (), and replace () methods of Fragmentmanager dynamically adding, removing, and replacing fragment while the activity is running.

1) Let's take a look at the class diagrams of various fragment base classes:

2) Let's look at the life cycle of the fragment and compare it to the life cycle of the activity:

Usage of 6.Fragment

1) Create fragment

Creating fragment typically implements the following three methods:
OnCreate (), Oncreateview (), OnPause ()

In order to control the components displayed by the fragment, it is often necessary to override the Oncreateview () method, which returns the view as the view component displayed by the fragment.

Override this method, the view returned by the method will be the component displayed as fragment @OverrideOncreateviewreturn view;}  

2) Add fragment to activity

There are two ways to add fragment to activity:

1th: Use the < fragment.../> element in the layout file to add fragment,<fragment.../> elements of Android: The Name property specifies the implementation class for the fragment. 2nd: Add fragment in Java code through the Add () method of the Fragmenttransaction object. The activity's Getfragmentmanager () method returns the BeginTransaction () of the Fragmentmanager,fragmentmanager object method to turn on and return the Fragmenttransaction object. 

3) How to add, update, and delete fragment dynamically in the activity?

You first need to add framelayout (set ID to FL) in the mainactivity layout file, and then simply create a two fragment (Myfragment and Twofragment) as follows:

public  class myfragment extends fragment { @Override  public View oncreateview ( Layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {return Inflater.inflate (R.layout.fragment_my, container, false);}}     
Oncreateviewfalse);}}

Next you can add, update, and delete fragment dynamically in mainactivity, and the method called in Mainactivity is as follows:

Set the default Fragmentfragmentmanager FM = Getfragmentmanager ();  Fragmenttransaction transaction = Fm.begintransaction ();  new Myfragment ();  Transaction.replace (R.ID.FL, myfragment);  Transaction.commit ();

If you click on a button to update fragment, the button click event is as follows:

@Override  onClick//Transaction submission Transaction.commit ();} 

"Reproduced" in Android development skillfully use activity and 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.