Android Fragment everything you should know

Source: Internet
Author: User

Reprint please indicate source: http://blog.csdn.net/lmj623565791/article/details/42628537, this article from: "Zhang Hongyang's Blog"

A long time ago wrote two Fragment introduction, mainly is to introduce its function: Android Fragment Real full resolution (on) and Android Fragment Real full parsing (under) interested can make it look under. Before the blog belongs to how to use fragment, this article aims to teach you how to use the good fragment, that is, fragment some of the suggestions, (most of the content from: Android programming the Big Nerd Ranch guide book, direct Baidu , you know, although it is a basic book, it is well worth seeing).

1. Overview

First of all, we have a brief review, I believe that everyone is not unfamiliar with the fragment, for the use of fragment, on the one hand, the activity needs to arrange for fragment in the layout, on the other hand need to manage the life cycle of fragment. The activity has a fragmentmanager that internally maintains the fragment queue and the fallback stack for fragment transactions.

In general, we add fragment in the activity:

public class Mainactivity extends Fragmentactivity{private contentfragment mcontentfragment  ; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_ Main); Fragmentmanager fm = Getsupportfragmentmanager (); mcontentfragment = (contentfragment) Fm.findfragmentbyid (R.id.id_ Fragment_container); if (mcontentfragment = = null) {mcontentfragment = new contentfragment (); Fm.begintransaction (). Add (r.id.id_fragment_container,mcontentfragment). commit ();}}}

For the above code, ask two questions:

1. Why do I need to be sentenced to null?

The main reason is that when the activity is killed by the system because of configuration changes (screen rotation) or the memory is not enough, our fragment will be saved, but a new fragmentmanager will be created. The new Fragmentmanager will first get the saved fragment queue, rebuild the fragment queue, and restore the previous state.

2. What is the ID of the layout in the Add (r.id.id_fragment_container,mcontentfragment) function?

On the one hand, it is to inform Fragmentmanager, the position of this fragment; On the other hand is the unique identity of this fragment; just like us through Fm.findfragmentbyid (R.id.id_fragment_ Container) Find ~ ~

OK, briefly review the basic usage, please refer to the above blog or other information, then, introduce some of the use of the comments ~ ~


2, Fragment Arguments

The following describes a simple scenario, such as when one of our buttons triggers an activity jump and needs to pass a parameter through intent to the target activity's fragment, how does this fragment get the current intent value?

Some guys would say, this is simple? Look at my Code (problem code):

public class Contentfragment extends Fragment{private string margument, public static final String ARGUMENT = "ARGUMENT"; overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); margument = Getactivity ( ). Getintent (). Getstringextra (ARGUMENT);}

We directly in the fragment OnCreate, get the host activty, the host activity will certainly be able to get intent through getintent, and then through the Get method, feel free to take parameters ~ ~

In this case, the function is realized, but what? There is a big problem: one of the big reasons we use fragment is to reuse. You write this, the equivalent of this fragment has been completely and the current host activity binding, reuse directly waste ~ ~ ~ So? We recommend using arguments to create fragment in a different way.

public class Contentfragment extends Fragment{private string margument;public static final String ARGUMENT = "ARGUMENT"; @O verridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);//margument = Getactivity (). Getintent (). Getstringextra (ARGUMENT); Bundle bundle = Getarguments (); if (bundle! = null) Margument = bundle.getstring (ARGUMENT);}  /** * Incoming required parameters, set to arguments * @param argument * @return */public static contentfragment newinstance (String argument) {Bundle bundle = new Bundle (); bundle.putstring (ARGUMENT, ARGUMENT); Contentfragment contentfragment = new Contentfragment (); contentfragment.setarguments (bundle); return contentfragment ;}

Add Newinstance method to fragment, pass in the required parameters, set to bundle, then setarguments (bundle), and finally get in oncreate;

This completes the decoupling between the fragment and the activity. Of course, here's what to note:

the Setarguments method must be completed before it is added to the activity after fragment is created . Never, first call the Add, and then set the arguments.


3, Fragment's Startactivityforresult

Still a simple scene: Two fragment, a fragment (called listtitlefragment) showing the list of articles, a fragment (called: contentfragment) with detailed information, of course, All two of these fragment have their host activity.

Now, we click the list fragment in the list item, pass in the corresponding parameter, go to detailed information fragment show detailed information, on the detail page, the user can carry on the review, when the user clicks back, The results of our previous reviews are shown in the list of fragment for the list item;

In other words, we click to jump to the corresponding activity of the fragment, and we want it to return parameters, then we must be using Fragment.startactivityforresult;

There are Startactivityforresult () and Onactivityresult () methods in fragment, but there is no Setresult () method for setting the returned intent, So we need to call Getactivity (). Setresult (Listtitlefragment.request_detail, intent);.

Detailed code:

Listtitlefragment

public class Listtitlefragment extends listfragment{public static final int request_detail = 0x110;private list<string > mtitles = arrays.aslist ("Hello", "World", "Android");p rivate int mcurrentpos; Private arrayadapter<string> Madapter; @Overridepublic void onactivitycreated (Bundle savedinstancestate) {super.onactivitycreated (savedinstancestate); Setlistadapter (madapter = new arrayadapter<string> (Getactivity (), Android. R.layout.simple_list_item_1, Mtitles));} @Overridepublic void Onlistitemclick (ListView l, View v, int position, long id) {mcurrentpos = position; Intent Intent = new Intent (getactivity (), contentactivity.class); Intent.putextra (Contentfragment.argument, Mtitles.get (position)); Startactivityforresult (Intent, request_detail);} @Overridepublic void Onactivityresult (int requestcode, int resultcode, Intent data) {LOG.E ("TAG", "Onactivityresult"); Super.onactivityresult (Requestcode, ResultCode, data), if (Requestcode = = Request_detail) {Mtitles.set (MCurrentPos, Mtitles. Get (Mcurrentpos) + "--" +data.getstringextra (Contentfragment.response)); madapter.notifydatasetchanged ();}} 


Contentfragment
public class Contentfragment extends Fragment{private string margument;public static final String ARGUMENT = "ARGUMENT";p u Blic static final String RESPONSE = "RESPONSE"; @Overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Bundle bundle = Getarguments (); if (bundle! = null) {margument = bundle.getstring (ARGUMENT); Intent Intent = new Intent (); int Ent.putextra (RESPONSE, "good"); Getactivity (). Setresult (Listtitlefragment.request_detail, Intent);}} public static contentfragment newinstance (String argument) {Bundle bundle = new Bundle (); bundle.putstring (argument, argument); Contentfragment contentfragment = new Contentfragment (); contentfragment.setarguments (bundle); return contentfragment ;} @Overridepublic View Oncreateview (layoutinflater inflater, ViewGroup container,bundle savedinstancestate) {Random Random = new Random (); TextView TV = new TextView (getactivity ()); Tv.settext (margument); tv.setgravity (Gravity.center); Tv.setbackgroundcolor (Color.argb (random.nextint(+), Random.nextint (255), Random.nextint (255), Random.nextint (255)); return TV;}} 

Posted two fragment of code, You can see that we are in Listtitlefragment.onlistitemclick, using Startactivityforresult () to jump to the target activity and get it in the target activity's fragment (Contentfragment) parameter, and then call Getactivity (). Setresult (Listtitlefragment.request_detail, intent); Set the returned data Finally, the Listtitlefragment.onactivityresult () gets the returned data for Echo;

For everyone in the future when encountering similar problems, provided a solution, also explained a problem:fragment can receive the return result from the activity, but its self-setting cannot produce the return result, only activity has the return result .

Next I'm going to post the two fragment hosting activity:

Listtitleactivity

public class Listtitleactivity extends Fragmentactivity{private listtitlefragment mlistfragment; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_ Single_fragment); Fragmentmanager fm = Getsupportfragmentmanager (); mlistfragment = (listtitlefragment) Fm.findfragmentbyid (R.id.id_ Fragment_container); if (mlistfragment = = null) {mlistfragment = new listtitlefragment (); Fm.begintransaction (). Add ( r.id.id_fragment_container,mlistfragment). commit ();}}}


Contentactivity:

public class Contentactivity extends Fragmentactivity{private contentfragment mcontentfragment; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_ Single_fragment); Fragmentmanager fm = Getsupportfragmentmanager (); mcontentfragment = (contentfragment) Fm.findfragmentbyid (R.id.id_ Fragment_container); if (mcontentfragment = = null) {String title = Getintent (). Getstringextra (contentfragment.argument ); mcontentfragment = contentfragment.newinstance (title); Fm.begintransaction (). Add (R.id.id_fragment_container, mcontentfragment). commit ();}}}

Did you find that the code in the two activity is extremely similar and uses the same layout file:

Activity_single_fragment.xml

<relativelayout 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:id= "@+id/id_fragment_container" ></RelativeLayout>

Why do you want to post this acticity code? Because in our project, if we use Fragment in principle, we will find a lot of similar code, then we can abstract an activity out and host our single Fragment.

See the next section in detail.


4, Singlefragmentactivity

So the code for the abstract activity is:

Package Com.example.demo_zhy_23_fragments;import Android.os.bundle;import Android.support.v4.app.fragment;import Android.support.v4.app.fragmentactivity;import Android.support.v4.app.fragmentmanager;public Abstract class Singlefragmentactivity extends fragmentactivity{protected abstract Fragment createfragment (); @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_single_ fragment); Fragmentmanager fm = Getsupportfragmentmanager (); Fragment Fragment =fm.findfragmentbyid (R.id.id_fragment_container); if (Fragment = = null) {Fragment = Createfragment (); Fm.begintransaction (). Add (R.id.id_fragment_container,fragment). commit ();}}}

So, with this singlefragmentactivity, our contentactivity and listtitleactivity can also be greatly changed ~

Package Com.example.demo_zhy_23_fragments;import Android.support.v4.app.fragment;public Class ContentActivity Extends Singlefragmentactivity{private contentfragment mcontentfragment; @Overrideprotected Fragment createfragment ( {String title = Getintent (). Getstringextra (contentfragment.argument); mcontentfragment = Contentfragment.newinstance (title); return mcontentfragment;}}

Package Com.example.demo_zhy_23_fragments;import Android.support.v4.app.fragment;public Class ListTitleActivity Extends Singlefragmentactivity{private listtitlefragment mlistfragment; @Overrideprotected Fragment createfragment () {mlistfragment = new listtitlefragment (); return mlistfragment;}}

is not a lot of concise, I believe that priority to use fragment project, similar activity is very much, use singlefragmentactivity to simplify your code bar ~ ~

OK, this code is from the beginning of the article recommended book, again recommended ~ ~.


5, Fragmentpageradapter and Fragmentstatepageradapter

Believe that the two pageradapter of the sub-class, we are not unfamiliar it ~ ~ Since the advent of fragment, the use of Viewpager combined with any one of the above examples of the production of the app homepage is particularly many cases ~ ~ ~

So what's the difference between these two classes?

The main difference is with regard to whether the fragment is destroyed, as follows:

Fragmentpageradapter: For fragment that are no longer needed, choose to call the Detach method, destroy the view only, and do not destroy the fragment instance.

Fragmentstatepageradapter: The fragment that is no longer needed will be destroyed, and when the current transaction commits, it will completely remove the Fragmeng from the current activity's Fragmentmanager, the state is marked, destroyed, The bundle information in its onsaveinstancestate (bundle outstate) is saved, and when the user switches back, a new fragment can be generated through the bundle, that is, You can save some data in the Onsaveinstancestate (Bundle outstate) method and create the restore in OnCreate.

As mentioned above, using Fragmentstatepageradapter is of course more memory-saving, but destroying new ones takes time. In general, if you are making the main page, on 3, 4 tab, then you can choose to use Fragmentpageradapter, if you are used for Viewpager display a very large number of entries, Then it is recommended to use Fragmentstatepageradapter.

The reason for the length, the specific case will not write, we self-test.


6. Data transfer between fragment

Above 3, we show the data transfer between the general two fragment.

Then there is a special case, that is, two fragment in the same activity: for example, click on the current Fragment button, pop up a dialog (dialogfragment), the Action in the dialog box needs to be returned to the trigger fragment, So what about data transfer? Recommended for use with dialog boxes: Android Official Recommendation: dialogfragment Create dialog box

We continue to modify our code: Now is Listtitlefragment, contentfragment, add a dialog box: Evaluatedialog, the user clicks the Contentfragment content to pop up a review list, the user selects the evaluation.

Now our focus is on how to gracefully get the evaluatedialog back in the contentfragment:

Remember that we are in an activity, then certainly not using Startactivityforresult, but the data we return is still being received in Onactivityresult.

Okay, look at the code:

Contentfragment

public class Contentfragment extends Fragment{private string margument;public static final String ARGUMENT = "ARGUMENT";p u Blic static final String RESPONSE = "RESPONSE";p ublic static final String evaluate_dialog = "Evaluate_dialog";p ublic Stati c final int request_evaluate = 0x110;//... @Overridepublic View oncreateview (layoutinflater inflater, ViewGroup container , Bundle savedinstancestate) {Random random = new random (); TextView TV = new TextView (getactivity ()); Viewgroup.layoutparams params = new Viewgroup.layoutparams (layoutparams.match_parent, layoutparams.match_parent); Tv.setlayoutparams (params); Tv.settext (margument); tv.setgravity (Gravity.center); Tv.setbackgroundcolor ( Color.argb (Random.nextint), Random.nextint (255), Random.nextint (255), Random.nextint (255)));//Set Clicktv.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {Evaluatedialog dialog = new Evaluatedialog ();//Note settargetfragmentdialog.settargetfragment (Contentfragment.this, REQUEST_EVALUATE);d ialOg.show (Getfragmentmanager (), evaluate_dialog);}); return TV;} Receive back Data @overridepublic void Onactivityresult (int requestcode, int resultcode, Intent data) {Super.onactivityresult (Requestcode, ResultCode, data); if (Requestcode = = request_evaluate) {String EVALUATE = Data.getstringextra ( Evaluatedialog.response_evaluate); Toast.maketext (Getactivity (), evaluate, Toast.length_short). Show (); Intent Intent = new Intent (); Intent.putextra ( RESPONSE, evaluate); Getactivity (). Setresult (Listtitlefragment.request_detail, Intent);}}

Removed some extraneous code, notice that we added the Click event for TextView in Oncreateview to pop up our dialog and note one line of code:

Dialog.settargetfragment (Contentfragment.this, request_evaluate);

We call the Fragment.settargetfragment, this method, is generally used for the current fragment by other fragment start, after the completion of the operation to return data, according to our needs ~ ~ ~ ~ Note that this sentence is very important.

Next look at the Evaluatedialog code:

Package Com.example.demo_zhy_23_fragments;import Android.app.activity;import Android.app.alertdialog;import Android.app.dialog;import Android.content.dialoginterface;import Android.content.DialogInterface.OnClickListener ; Import Android.content.intent;import Android.os.bundle;import Android.support.v4.app.dialogfragment;public class Evaluatedialog extends dialogfragment{private string[] mevalutevals = new string[] {"Good", "bad", "NORMAL"};p ublic Stat IC final String response_evaluate = "Response_evaluate"; @Overridepublic Dialog Oncreatedialog (Bundle Savedinstancestate) {Alertdialog.builder Builder = new Alertdialog.builder (getactivity ()); Builder.settitle (" Evaluate: "). Setitems (Mevalutevals,new Onclicklistener () {@Overridepublic void OnClick (dialoginterface dialog, int which) {setresult (which);}}); return Builder.create ();} Sets the return data protected void Setresult (int which) {//Determines whether Targetfragmentif (gettargetfragment () = = null) is set return;intent Intent = new Intent (); Intent.putextra (Response_evaluatE, Mevalutevals[which]); Gettargetfragment (). Onactivityresult (Contentfragment.request_evaluate,activity.result_ OK, intent);}}

The point is to see the Setresult after the click, we first determine whether to set the Targetfragment, if set, it means we want to return some data to targetfragment.

We create the intent package to pass the data, and finally manually call Onactivityresult to return the data ~ ~

Finally, we can receive it in the Contentfragment Onactivityresult.


OK, finally put these tips through together, to this our fragment some of the recommendations of the use of the end ~ ~ ~ So, finally provide the next source, also by the way to paste a:






SOURCE Click to download




I built a QQ group, convenient for everyone to communicate. Group number:423372824

----------------------------------------------------------------------------------------------------------

Bo Master part of the video has been online, if you do not like boring text, please poke (first record, look forward to your support):

1, the use of Baidu map in Android

2. Android custom control Scratch card in real-action e-commerce activities

3. Android custom controls build Android streaming layouts and popular tags

4. android Robot "Little Mu" implementation

5, High imitation QQ5.0 slide

6, High imitation 5.2.1 main interface and message alert






Android Fragment everything you should know

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.