Fragment of "Android development" and acitvity communication

Source: Internet
Author: User

In the previous article we talked about the frequent use of functions related to fragment, since fragment is called "small activity". Now let's talk about how fragment communicates with Acitivity. Suppose the last article still does not understand. can look again.

Portals.

the way fragment communicates with activity is as follows:first, through the initialization function to provide

   1. In the process of dynamically joining Fragment, we provide data for Fragment in activity through the fragment.setarguments () method.

2. In fragment, a bundle object is obtained by calling Getarguments () in the Onattach () function to obtain the data we provide.

second, create callback interface

   For example: In the context of news browsing, there are two fragment together. One is used to display news headlines, and the other is used to display news content.

When we click on the news headlines, the content of the news is displayed to another fragment.

Let's do this by pressing the button in Fragment1 to pass a message to Fragment2.

The first thing we need to do is to create a callback interface in Fragment1, and rewrite his method in the activity, passing the message to Fragment2(extrapolate: We can also pass to the other fragment).

Here's the code I gave Fragment1:

Package Com.example.fragment;import Android.app.activity;import Android.os.bundle;import Android.support.v4.app.fragment;import Android.util.attributeset;import Android.util.log;import Android.view.layoutinflater;import Android.view.view;import Android.view.view.onclicklistener;import Android.view.viewgroup;import Com.example.fragmentdemo.r;public class Fragment1 extends Fragment {private static final String TAG = "Fragmentdemo";p rivate onbuttonclicklistener mlistener;/** * Here we create a callback interface * * @author MYP * */public interf Ace Onbuttonclicklistener {public void onbuttonclicked ();} @Overridepublic void Onattach (activity activity) {LOG.V (TAG, "Fragment1 Onattach"); Bundle args = Getarguments (); if (null! = args) {/* * Here we can save the data received from acivity and display it to fragment. */LOG.D (TAG, "Fragment1 Get data from activity" + args.getstring ("Hello"));} try {Mlistener = (Onbuttonclicklistener) activity;} catch (ClassCastException e) {throw new ClassCastException ( Activity.tostring () + "must implement OnbuttonclicKlistener ");} Super.onattach (activity);} @Overridepublic void oninflate (activity activity, AttributeSet Attrs,bundle savedinstancestate) {log.d (TAG, "oninflate "); Super.oninflate (activity, attrs, savedinstancestate);} @Overridepublic void OnCreate (Bundle savedinstancestate) {log.v (TAG, "Fragment1 onCreate"); Super.oncreate ( Savedinstancestate);} @Overridepublic void OnDestroy () {LOG.V (TAG, "Fragment1 OnDestroy"); Super.ondestroy ();} @Overridepublic void Onresume () {LOG.V (TAG, "Fragment1 onresume"); Super.onresume ();} @Overridepublic void OnStart () {LOG.V (TAG, "Fragment1 OnStart"); Super.onstart ();} @Overridepublic void Ondetach () {LOG.V (TAG, "Fragment1 Ondetach"); Super.ondetach ();} @Overridepublic void OnPause () {LOG.V (TAG, "Fragment1 onPause"); Super.onpause ();} @Overridepublic void OnStop () {LOG.V (TAG, "Fragment1 onStop"); Super.onstop ();} @Overridepublic View Oncreateview (layoutinflater inflater, ViewGroup container,bundle savedinstancestate) {Log.v (TAG, "Fragment1 Oncreateview"); View view = Inflater. Inflate (R.layout.fragment1, container, false);//For the button register event, and call the callback interface to return the information to the upper View.findviewbyid (r.id.fragment1_ BTN). Setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {mlistener.onbuttonclicked ();}}); return view;} @Overridepublic void Ondestroyview () {LOG.V (TAG, "Fragment1 Ondestroyview"); Super.ondestroyview ();} @Overridepublic void onactivitycreated (Bundle savedinstancestate) {log.v (TAG, "Fragment1 onactivitycreated"); Super.onactivitycreated (savedinstancestate);}}

1. Create the callback interface.

2. To ensure that the host activity implements this interface, the Fragment1 Onattach () method instantiates an Onbuttonclicklistener object by casting the incoming activity coercion type;

3. Register the button's Click event and invoke the callback method in the event.

Then I give the code for the activity:

Package Com.example.fragmentdemo;import Android.annotation.suppresslint;import Android.os.bundle;import Android.support.v4.app.fragment;import Android.support.v4.app.fragmentactivity;import Android.support.v4.app.fragmenttransaction;import Android.util.log;import Android.widget.textview;import Com.example.fragment.fragment1;import Com.example.fragment.fragment1.onbuttonclicklistener;import Com.example.fragment.Fragment2, @SuppressLint ("Recycle") public class Mainactivity extends fragmentactivity Implementsonbuttonclicklistener {private static final String TAG = "Fragmentdemo";p rivate Fragment1 fragment1;private Fragment2 fragment2; @Overrideprotected void OnCreate (Bundle savedinstancestate) {log.i (TAG, "onCreate"); Super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); fragment1 = new Fragment1 (); Fragment2 = New Fragment2 (); AddFragment1 (); AddFragment2 ();} private void AddFragment1 () {Bundle args = new Bundle (); Args.putstring ("Hello", "Hello Fragment1"); Fragment1.setargumeNTS (args); LOG.I (TAG, "Create Fragment1"); Fragmenttransaction transaction = Getsupportfragmentmanager (). BeginTransaction (); Transaction.settransition ( Fragmenttransaction.transit_fragment_open); Transaction.add (R.id.one, fragment1); Transaction.addtobackstack (null ); Transaction.commit ();} private void AddFragment2 () {Bundle args = new Bundle (); Args.putstring ("Hello", "Hello Fragment2"); Fragment2.setarguments (args); LOG.I (TAG, "Create Fragment2"); Fragmenttransaction transaction = Getsupportfragmentmanager (). BeginTransaction (); Transaction.settransition ( Fragmenttransaction.transit_fragment_open); Transaction.replace (R.id.two, Fragment2); Transaction.addtobackstack ( NULL); Transaction.commit ();} @Overridepublic void Onattachfragment (Fragment Fragment) {log.i (TAG, "onattachfragment"); Super.onattachfragment ( fragment);} @Overrideprotected void OnDestroy () {log.i (TAG, "OnDestroy"); Super.ondestroy ();} @Overrideprotected void OnPause () {log.i (TAG, "OnPause"); Super.onpause ();} @Overrideprotected void Onresume (){LOG.I (TAG, "Onresume"); Super.onresume ();} @Overrideprotected void OnStart () {log.i (TAG, "OnStart"); Super.onstart ();} @Overrideprotected void OnStop () {log.i (TAG, "onStop"); Super.onstop ();} @Overrideprotected void Onrestart () {log.i (TAG, "Onrestart"); Super.onrestart ();} @Overridepublic void OnButtonClicked () {log.i (TAG, "onbuttonclicked"); TextView TV = (TextView) fragment1.getactivity (). Findviewbyid (R.ID.FRAGMENT2_TV); Tv.settext (Tv.gettext () + "\ n Receive data from Fragment1!

");}}


1. Implement the callback interface via implements .

2. Rewrite the callback method and pass the data to Fragment2.

Third, source code download

Click I download. Download the source code into project and you can use it!

The next step may be to introduce the fragment animation effect. Interested to have a look.

Fragment of "Android development" and acitvity communication

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.