Virgin Male Learn Android (10)---fragment end of fragment communication and Listfragment

Source: Internet
Author: User
Tags instance method



First, preface



The first two blogs introduce the basic usage of fragment

1.Fragment API Introduction: such as Fragmentmanager, fragmenttransaction and so on.

2. How to define: Inherit the Fragment class and rewrite Oncreat, Oncreatview, OnPause, and so on.

3. Citation: Fragment are added dynamically by defining the <fragment> tag or by adding () the Fragmenttrasaction instance.

4.Fragment fallback stack with fragment life cycle.

About fragment the rest of the important points of knowledge is almost the rest of the following:

1.Fragment communication with activity, fragment, and fragment.

How to use 2.ListFragment.

3. Other related fragmented knowledge points.

This blog will proceed to record the following three points mentioned above, about fragment introduction to this article is over.



Second, fragment communication



A.fragment and Activity Communication


We usually manage fragment in activity, so the general activity should have references to all the fragment that are attached to it, so you can access the fragment method directly in the activity by instantiating the fragment object. Look at a simple code:

Package Com.example.fragmenttransdemo;import Android.app.activity;import Android.app.fragmentmanager;import Android.app.fragmenttransaction;import Android.os.bundle;public class Mainactivity extends Activity {private Fragmentmanager fm;private fragmenttransaction ftx;private fragmentleft fleft;private FragmentRight fRight;@ overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.LAYOUT.ACTIVITY_MAIN); fm = Getfragmentmanager (); ftx = Fm.begintransaction (); fleft = new Fragmentleft (); fRight = new Fragmentright (); Ftx.add (R.id.fm_left, Fleft, "left"), Ftx.add (R.id.fm_right, Fright, "right"); Ftx.commit ();}}

So what if there are no fragment references in the activity, such as when we introduced fragment in the activity's layout file through the <fragment> tag, the answer is simple, and in the first API it's simply mentioned, Each fragment can specify an ID or tag, via Fragmentmanager instance method:Findfragmentbyid or Findfragmentbytag You can find the specified fragment. For example, the following:

Layout file Code

<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:paddingbottom= "@dimen/activity_vertical_margin"    android:paddingleft= "@dimen/activity_ Horizontal_margin "    android:paddingright=" @dimen/activity_horizontal_margin "    android:paddingtop=" @dimen /activity_vertical_margin "    tools:context=" com.example.fragmentbasedemo.MainActivity ">    <fragment        android:id= "@+id/fm_one"        android:name= "Com.example.fragmentbasedemo.FragmentOne"        android:layout _width= "Match_parent"        android:layout_height= "match_parent"        android:tag= "Fragment_one_tag"/></ Relativelayout>

Activity Code

Package Com.example.fragmentbasedemo;import Android.app.activity;import Android.app.fragmentmanager;import Android.os.bundle;import Android.util.log;import Android.widget.toast;public class Mainactivity extends Activity { private static final String TAG = "mainactivity";p rivate fragmentmanager fm;private fragmentone fOne; @Overrideprotected V OID onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); LOG.I (TAG, "onCreate"); Setcontentview (r.layout.activity_main); fm = Getfragmentmanager (); fOne = (Fragmentone) Fm.findfragmentbyid (R.id.fm_one); String Fonetag = Fone.gettag (); Toast.maketext (Mainactivity.this, "fonetag:\n" + Fonetag,toast.length_long). Show ();}}
you can see that we have defined the ID and tag for fragment in the layout file, and we can find the fragment through Findfragmentbyid in the code, and we will get the fragment tag information successfully:


After watching the operation of fragment in the activity, then look at how to manipulate the activity in fragment, very simple, in fragment by calling Getactivity () You can get the activity that the current fragment binds to and manipulate it.


In addition to the basic interactions, data transfer may be required, in the same way as in two cases:

1.Activity Passing data to fragment (byBundle)

Create bundle packets in activity and call fragment's setarguments (Bundle B) method bundle packet to fragment.

2.Fragment Passing data to activity (callback interface)

The callback interface is now more elaborate.


b . Fragment and Fragment communication


The simplest solution has been mentioned above, also through the Fragmentmanager instance method Findfragmentbytag can be found by this tag any fragment of the sibling. The same example of giving a small snippet of code:

Package Com.example.fragmenttransdemo;import Android.app.fragment;import Android.app.fragmentmanager;import Android.os.bundle;import Android.view.layoutinflater;import Android.view.view;import Android.view.ViewGroup; Import Android.widget.button;import Android.widget.edittext;import Android.widget.toast;public class FragmentLeft Extends Fragment {Private Button button;private fragmentmanager FM; @Overridepublic void OnCreate (Bundle Savedinstancestate) {//TODO auto-generated method Stubsuper.oncreate (savedinstancestate);} @Overridepublic View Oncreateview (layoutinflater inflater, ViewGroup container,bundle savedinstancestate) {//TODO Auto-generated method Stubview view = inflater.inflate (R.layout.left, null); button = (Button) View.findviewbyid ( R.id.btn_left); Button.setonclicklistener (new View.onclicklistener () {@Overridepublic void OnClick (View v) {//TODO Auto-generated Method STUBFM = Getfragmentmanager ();//Get the Fragmentfragment fright = Fm.findfragmentbytag ("right"). View view = FrighT.getview (); EditText et = (EditText) View.findviewbyid (r.id.et_right); String rightinfo = Et.gettext (). toString (); Toast.maketext (Getactivity (), Rightinfo, Toast.length_long). Show ();}); return view;} @Overridepublic void OnPause () {//TODO auto-generated method Stubsuper.onpause ();}}

Very simple, in Fragmentleft, first find the fragmentright by tag, then get the value of the fragment layout and pop up.


In addition to simple data lookup, sometimes we also have operational needs, such as the previous blog example, Fragmentone put a ListView, when clicked on the item to replace the current fragment, In the previous blog I practice is directly in the Onitemclick event of the ListView to perform the Fragmentmanager replacement method to replace, note that this is not advisable, regardless of the Android reference book, This is also mentioned in Yang's blog:fragment should be managed by the activity . Therefore, the general standard practice is: If you need to operate a fragment, you should first define a callback interface within it, and then implement this interface in the activity and implement an abstract method of the interface, when the need for fragment operation, Callback the implementation of the activity in the fragment .

The following is a perfect example of the previous blog, the same is two Fragment,fragmentone put a ListView, when you click on the item to replace the fragment and pass the value to the new fragment, the first is the fragment code:

Package Com.example.fragmentbasedemo;import Android.app.activity;import Android.app.fragment;import Android.os.bundle;import Android.view.layoutinflater;import Android.view.view;import Android.view.ViewGroup; Import Android.widget.adapterview;import Android.widget.adapterview.onitemclicklistener;import Android.widget.listview;public class Fragmenttwo extends Fragment implements Onitemclicklistener {private ListView lv;@ overridepublic void Onattach (activity activity) {//TODO auto-generated method Stubsuper.onattach (activity);} @Overridepublic void OnCreate (Bundle savedinstancestate) {//TODO auto-generated method Stubsuper.oncreate ( Savedinstancestate);} @Overridepublic View Oncreateview (layoutinflater inflater, ViewGroup container,bundle savedinstancestate) {//TODO Auto-generated method Stubview v = inflater.inflate (r.layout.fragment_list, null); LV = (ListView) V.findviewbyid ( r.id.lv_hero_list); Lv.setonitemclicklistener (this); return v;} @Overridepublic void OnPause () {//TODO Auto-generatEd method Stubsuper.onpause ();} @Overridepublic void Onitemclick (adapterview<?> parent, view view, int Position,long ID) {//Determine if activity implements this interface if (Getactivity () instanceof Monitemclicklistener) ((Monitemclicklistener) getactivity ()). Onitemclick (view);} public interface Monitemclicklistener {void Onitemclick (view view);}}

then look at the code in the activity:

Package Com.example.fragmentbasedemo;import Com.example.fragmentbasedemo.fragmenttwo.monitemclicklistener;import Android.app.activity;import Android.app.fragmentmanager;import Android.app.fragmenttransaction;import Android.os.bundle;import Android.util.log;import Android.view.view;import Android.widget.textview;public class Mainactivity extends Activity implements Monitemclicklistener {private static final String TAG = "mainactivity";p rivate Fr Agmentmanager fm;private fragmenttransaction ftx;private fragmenttwo ftwo;private FragmentThree fThree;@ overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); LOG.I (TAG, "onCreate"); Setcontentview (r.layout.activity_main); fm = Getfragmentmanager (); ftx = Fm.begintransaction () ; ftwo = new Fragmenttwo (); Ftx.add (R.id.fl_container, Ftwo, "Fragment_two"); Ftx.commit ();} @Overridepublic void Onitemclick (view view) {Bundle b = new Bundle (); TextView TV = (TextView) view;b.putcharsequence ("Text", Tv.gettext ()); if (fthree = = null) {Fthree = new Fragmentthree (); fthree.setarguments (b);} fm = Getfragmentmanager (); ftx = Fm.begintransaction (); Ftx.replace (R.id.fl_container, Fthree, "Fragment_three"); Ftx.commit ();}}

The benefits of doing so are obvious, such as:

1. The coupling between activity and fragment is reduced, and the reuse rate of fragment is improved.

2. You can manage any fragment directly in the activity.

3. The flexibility of the program, which is also one of the benefits of decoupling, requires processing the implementation interface and does not need processing to be implemented.

4. Convenient transfer value, such as the parameter view.



Third, listfragment



The listfragment is usually suitable for fragment with only one ListView, because Listfragment does not need a layout, it only needs to provide a adapter, and through Listfragment's Setlistadapter (ListAdapter adapter) can be implemented, very simple, not too much explanation, paste a sample code (activity code is not posted, Listfragment also when fragment to operate can):

Package Com.wl.lfd;import Java.util.arraylist;import Java.util.list;import android.app.listfragment;import Android.os.bundle;import Android.view.view;import Android.widget.arrayadapter;import Android.widget.ListAdapter; Import Android.widget.listview;import Android.widget.toast;public class Mylistfragment extends Listfragment {private ListAdapter adapter; @Overridepublic void OnCreate (Bundle savedinstancestate) {//TODO auto-generated method Stubsuper.oncreate (savedinstancestate); list<string> datas = new arraylist<string> (); for (int i = 0; i <; i++) {Datas.add ("Druid" + i);} adapter = new Arrayadapter<string> (Getactivity (), Android. R.layout.simple_list_item_1, datas); Setlistadapter (adapter);} @Overridepublic void OnPause () {//TODO auto-generated method Stubsuper.onpause ();} @Overridepublic void Onlistitemclick (ListView l, View v, int position, long ID) {//TODO auto-generated method stubtoast.m Aketext (Getactivity (), Adapter.getitem (position). ToString (), toast.length_sHort). Show ();}} 

Here are the following:




Iv. Summary



About fragment Introduction to here is all over, follow up will continue to improve this several fragment articles, this series of "Virgin Male Learn Android" to this also came to an end, back to continue to learn what I still thinking, now feel what will be a little, and nothing, is irritable, Be prepared to develop a detailed and workable learning Plan and plan, and then come back to continue writing this series of blogs. There's still a lot to learn, raito!.

Virgin Male Learn Android (10)---fragment end of fragment communication and Listfragment

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.