Examples of interop code between fragment and activity in Android

Source: Internet
Author: User

Summary

This article describes how fragment can interoperate through activity when there are multiple fragment in an activity in Android.

Source

Source code address is: http://download.csdn.net/detail/logicteamleader/8931199
The source code is written using ADT and the ADT version is 2014,android version android-22.

Technical Essentials

1. In the activity of multiple fragment to interoperate between, must through this activity, cannot direct communication;
2. Add fragment in activity can use the ID or tag, it is recommended to use tag, so whether the fragment has no interface, can be found by the activity using Findfragmentbytag method;
3. Define the callback interface in fragment and let the activity implement this callback interface so that the activity can respond to messages in the fragment;
4. To interoperate between different fragment, or to implement callback interfaces through activity, such as the Onbtnaclicked method in callback mainactivity in Fragmenta, In the Onbtnaclicked method, the Fragmentb Changeb method is called, which achieves the interoperation between the two fragment.

Source code for Fragmenta
 PackageCom.apkkids.fragmentinactivityexample;Importandroid.app.Activity;ImportAndroid.os.Bundle;Importandroid.support.annotation.Nullable;ImportAndroid.support.v4.app.Fragment;ImportAndroid.view.LayoutInflater;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.view.ViewGroup;ImportAndroid.widget.Button;ImportAndroid.widget.TextView; Public  class fragmenta extends Fragment {    Private Static intIchange =1;PrivateTextView TvA;///callback interface, this interface must be implemented by mainactivity, and through this interface callback to do fragment and activity interoperability     PublicOnfragmentabtnclickedlistener Mcallback =NULL; Public  interface onfragmentabtnclickedlistener{         Public void onbtnaclicked(); }@Override     Public void Onattach(Activity activity) {Super. Onattach (activity);Try{mcallback = (onfragmentabtnclickedlistener) activity; }Catch(ClassCastException e) {Throw NewClassCastException (activity.tostring () +"must implement Onfragmentabtnclickedlistener"); }    }@Override    @Nullable     PublicViewOncreateview(Layoutinflater inflater, @Nullable viewgroup container, @Nullable Bundle savedinstancestate) {View v = inflater.inflate (r.layout.fragmenta_layout, container,false);        TvA = (TextView) V.findviewbyid (R.ID.TVA); Button Btna = (button) V.findviewbyid (R.id.buttona);//Click this button to change the TextView in FRAGMENTB via the callback interfaceBtna.setonclicklistener (NewOnclicklistener () {@Override             Public void OnClick(View v) {if(Mcallback! =NULL) {mcallback.onbtnaclicked (); }            }        });returnV } Public void Changea() {if(TvA! =NULL) {Tva.settext ("TextView in Fragmenta changed by FRAGMENTB:"+ ichange++); }    }}
Source code for FRAGMENTB
 PackageCom.apkkids.fragmentinactivityexample;Importandroid.app.Activity;ImportAndroid.os.Bundle;Importandroid.support.annotation.Nullable;ImportAndroid.support.v4.app.Fragment;ImportAndroid.view.LayoutInflater;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.view.ViewGroup;ImportAndroid.widget.Button;ImportAndroid.widget.TextView; Public  class fragmentb extends Fragment {    Private Static intIchange =1;PrivateTextView TvB;///callback interface, this interface must be implemented by mainactivity, and through this interface callback to do fragment and activity interoperability     PublicOnfragmentbbtnclickedlistener Mcallback =NULL; Public  interface onfragmentbbtnclickedlistener {         Public void onbtnbclicked(); }@Override     Public void Onattach(Activity activity) {Super. Onattach (activity);Try{mcallback = (onfragmentbbtnclickedlistener) activity; }Catch(ClassCastException e) {Throw NewClassCastException (activity.tostring () +"must implement Onfragmentbbtnclickedlistener"); }    }@Override    @Nullable     PublicViewOncreateview(Layoutinflater inflater, @Nullable viewgroup container, @Nullable Bundle savedinstancestate) {View v = inflater.inflate (r.layout.fragmentb_layout, container,false);        TvB = (TextView) V.findviewbyid (R.ID.TVB);        Button BTNB = (button) V.findviewbyid (R.ID.BUTTONB); Btnb.setonclicklistener (NewOnclicklistener () {@Override             Public void OnClick(View v) {if(Mcallback! =NULL) {mcallback.onbtnbclicked (); }            }        });returnV }/** * Change the value of text * /     Public void Changeb() {if(TvB! =NULL) {Tvb.settext ("TextView in Fragmentb changed by Fragmenta:"+ ichange++); }    }}
Source code for Mainactivity
 PackageCom.apkkids.fragmentinactivityexample;ImportAndroid.os.Bundle;Importandroid.support.v4.app.FragmentActivity;ImportAndroid.support.v4.app.FragmentManager;ImportAndroid.support.v4.app.FragmentTransaction;ImportAndroid.view.Menu;ImportAndroid.view.MenuItem;/** * @author An example of interoperability between multiple fragment in WXB * description:activity, mainly using the callback interface method implementation. * Note: There is no direct communication between fragment, must be through their attached activity * * 2015-7-24 * PM 10:02:45 * * Public  class mainactivity extends fragmentactivity implements  Fragmenta. Onfragmentabtnclickedlistener,fragmentb. Onfragmentbbtnclickedlistener {      Private Static FinalString Fragment_a_tag ="Com.apkkids.fragmentA";Private Static FinalString Fragment_b_tag ="Com.apkkids.fragmentB";@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main); Fragmenta Fragmenta =NewFragmenta (); FRAGMENTB FRAGMENTB =NewFRAGMENTB ();        Fragmentmanager Fragmentmanager = Getsupportfragmentmanager (); Fragmenttransaction transaction = Fragmentmanager.begintransaction ();//Use tag to add fragment, also can be added by ID methodTransaction.add (R.id.containera, Fragmenta, Fragment_a_tag);        Transaction.add (R.id.containerb, FRAGMENTB, Fragment_b_tag);    Transaction.commit (); }@Override     Public Boolean Oncreateoptionsmenu(Menu menu) {Getmenuinflater (). Inflate (R.menu.main, menu);return true; }@Override     Public Boolean onoptionsitemselected(MenuItem Item) {intid = item.getitemid ();if(id = = r.id.action_settings) {return true; }return Super. onoptionsitemselected (item); }/* (non-javadoc) * @see com.apkkids.fragmentinactivityexample.fragmenta.onaclickedlistener#onaclicked () * Frag A method of the callback interface defined in Menta, which modifies the UI in the FRAGMENTB * /    @Override     Public void onbtnaclicked() {//Get an example of FRAGMENTBFragmentmanager Fragmentmanager = Getsupportfragmentmanager (); FRAGMENTB FRAGMENTB = (FRAGMENTB) fragmentmanager.findfragmentbytag (Fragment_b_tag);if(Fragmentb! =NULL) Fragmentb.changeb (); }@Override     Public void onbtnbclicked() {//Get an example of FragmentaFragmentmanager Fragmentmanager = Getsupportfragmentmanager (); Fragmenta Fragmenta = (fragmenta) fragmentmanager.findfragmentbytag (Fragment_a_tag);if(Fragmenta! =NULL) Fragmenta.changea (); }}
Program Execution Interface

Summary

Other interface code should be downloaded from the source code package, no integration is required.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Examples of interop code between fragment and activity in Android

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.