Android uses broadcasts to achieve data communication between item in Viewpager

Source: Internet
Author: User

When you implement communication between fragment (for example, Fragment_a and Fragment_b), you might think of a way to provide an interface in Fragment_b, and then call the interface in Fragment_a and pass the required parameters in the past.

I'm going to use broadcast to deliver data from Fragment_a to Fragment_b.

Main interface:

public class Mainactivity extends fragmentactivity {private int getlayoutresid () {return R.layout.activity_mai    N    } private Myviewpageradapter madapter = null;    Private final int start_item = 0;        Private Viewpager Mdataviewpager = null;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        This.requestwindowfeature (Window.feature_no_title);                Setcontentview (Getlayoutresid ());    Initevent ();    }/** * Initialize event */private void Initevent () {Initview ();    }/** * Initialization interface */private void Initview () {initwidgets (); }/** * Initialize control */private void Initwidgets () {Mdataviewpager = (Viewpager) Findviewbyid (r.id.acti                Vity_main_show_viewpager);        Madapter = new Myviewpageradapter (Getsupportfragmentmanager ());        Madapter.setcontext (Mainactivity.this);       Mdataviewpager.setadapter (Madapter); Mdataviewpager.setcurrentitem (Start_item); }}

Adapter:

public class Myviewpageradapter extends Fragmentstatepageradapter {public static final int Fragment_viewpager_page_ COUNT = 2;private Context mcontext;public myviewpageradapter (fragmentmanager FM) {super (FM);} public void SetContext (context context) {        Mcontext = context;    } @Overridepublic Fragment getItem (int which) {try {switch (which) {case 0:return pageonefragment.newinstance (), Case 1: Return pagetwofragment.newinstance ();d efault:break;}} catch (Exception e) {    e.printstacktrace ();} return pageonefragment.newinstance ();} @Overridepublic int GetCount () {return fragment_viewpager_page_count;}}

The first of the fragment:

public class Pageonefragment extends Fragment {public static pageonefragment newinstance () {pageonefragment Fragment = new Pageonefragment (); return fragment;} private int Getlayoutresid () {return r.layout.fragment_page_0;} public static final String TAG = PageOneFragment.class.getName ();p rivate TextView mshowtextview = null;private Button Msen Dbutton = null;private static final int message_updateview = 0x123;private Pagetwodatachangedreceiver mReceiver = null;pub Lic static final String data_changed = "Com.example.viewpager.communication.fragment.PAGE_ONE_DATA_CHANGED"; Overridepublic View Oncreateview (Layoutinflater inflater, ViewGroup container,bundle savedinstancestate) {View view = Inflater.inflate (Getlayoutresid (), container, false); initevent (view); return view;} private void Initevent (View v) {Initview (v); Registerpagetwodatachangedreceiver ();} private void Initview (View v) {initwidgets (v); Setviewonclickevent ();} private void Initwidgets (View v) {Mshowtextview = (TextView) v.findViewbyid (R.id.page_0_show_textview); Msendbutton = (Button) V.findviewbyid (R.id.page_0_send_button);} /** * Click on all buttons to monitor */private void Setviewonclickevent () {Msendbutton.setonclicklistener (viewonclicklistener);} Private Onclicklistener Viewonclicklistener = new Onclicklistener () {@Overridepublic void OnClick (View v) {switch (V.geti    D ()) {case R.id.page_0_send_button:intent Intent = new Intent ();    Intent.setaction (pagetwofragment.data_changed); Getactivity (). Sendbroadcast (intent); break;default:break;}};    private void Registerpagetwodatachangedreceiver () {intentfilter filter = new Intentfilter ();            try {if (mreceiver! = null) {getactivity (). Unregisterreceiver (Mreceiver);        }} catch (Exception e) {e.printstacktrace ();    } mreceiver = new Pagetwodatachangedreceiver ();    Filter.addaction (pageonefragment.data_changed); Getactivity (). Registerreceiver (mreceiver, filter);} Handler Handler = new Handler () {public void Handlemessage (Message msg) {switch (msg.what) {case Message_updateview:updateview ((String) msg.obj); ;d efault:break;};}; private void Updateview (String data) {Mshowtextview.settext ("from the second page:" + Data + "" + System.currenttimemillis ());} Class Pagetwodatachangedreceiver extends Broadcastreceiver {@Override public void onreceive (context context  , Intent Intent) {if (Intent.getaction (). Equals (pageonefragment.data_changed)) {String label =                "Both time:";                Message msg = new Message ();                Msg.what = Message_updateview;                msg.obj = label;            Handler.sendmessage (msg); }}} @Overridepublic void OnDestroy () {if (mreceiver! = null) {getactivity (). Unregisterreceiver (MRec        Eiver); } Super.ondestroy ();}}

a second fragment:

public class Pagetwofragment extends Fragment {public static pagetwofragment newinstance () {pagetwofragment Fragment = new Pagetwofragment (); return fragment;} private int Getlayoutresid () {return r.layout.fragment_page_1;} public static final String TAG = PageTwoFragment.class.getName ();p rivate static final int message_updateview = 0x123;priva    Te TextView mshowtextview = null; Private Button Msendbutton = null;private pageonedatachangedreceiver mreceiver = null;public static final String Data_chan GED = "Com.example.viewpager.communication.fragment.PAGE_TWO_DATA_CHANGED"; @Overridepublic View Oncreateview ( Layoutinflater Inflater, ViewGroup container,bundle savedinstancestate) {View view = Inflater.inflate (GetLayoutResID () , container, false); initevent (view); return view;} private void Initevent (View v) {Initview (v); Registerpageonedatachangedreceiver ();} private void Initview (View v) {initwidgets (v); Setviewonclickevent ();} private void Initwidgets (View v) {Mshowtextview = (TextView) v.findViewbyid (R.id.page_1_show_textview); Msendbutton = (Button) V.findviewbyid (R.id.page_1_send_button);} /** * Click on all buttons to monitor */private void Setviewonclickevent () {Msendbutton.setonclicklistener (viewonclicklistener);} Private Onclicklistener Viewonclicklistener = new Onclicklistener () {@Overridepublic void OnClick (View v) {switch (V.geti                D ()) {case R.id.page_1_send_button:intent Intent = new Intent ();                Intent.setaction (pageonefragment.data_changed);    Getactivity (). Sendbroadcast (intent); break;default:break;}};        private void Registerpageonedatachangedreceiver () {intentfilter filter = new Intentfilter ();            try {if (mreceiver! = null) {getactivity (). Unregisterreceiver (Mreceiver);        }} catch (Exception e) {e.printstacktrace ();        } mreceiver = new Pageonedatachangedreceiver ();        Filter.addaction (pagetwofragment.data_changed); Getactivity (). registerreceIver (mreceiver, filter); } Handler Handler = new Handler () {public void Handlemessage (Message msg) {switch (msg.what) {case Message_updateview:u Pdateview (String) msg.obj); break;default:break;};}; private void Updateview (String data) {mshowtextview.settext ("data sent from the first page:" + Data + "" + System.currenttimemillis ()    ); } class Pageonedatachangedreceiver extends Broadcastreceiver {@Override public void OnReceive (Context Co ntext, Intent Intent) {if (Intent.getaction (). Equals (pagetwofragment.data_changed)) {String LA                Bel = "One time:";                Message msg = new Message ();                Msg.what = Message_updateview;                msg.obj = label;            Handler.sendmessage (msg); }}} @Override public void OnDestroy () {if (mreceiver! = null) {getactivity (). Unregis        Terreceiver (Mreceiver);    } Super.ondestroy (); }}

Project Source:

The layout file is relatively simple and is not given here. The following is the project source code.

http://download.csdn.net/detail/u013761665/8333283


the author's latest development of application connection

Http://zhushou.360.cn/detail/index/soft_id/2419729?recrefer=SE_D_%E6%A3%B1%E9%95%9C

Http://www.wandoujia.com/apps/com.mastershield.personalstat


Android uses broadcasts to achieve data communication between item in Viewpager

Related Article

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.