Android--------Object-oriented universal interface for activity and fragment communication

Source: Internet
Author: User
Tags eventbus

Objective

When developing an app, frequently used activity and fragment, due to the ease of operation fragment more and more popular, so as to avoid the activity and fragment, fragment and fragment communication, We know that fragment and fragment cannot communicate directly, but instead communicate through activity. So there are several ways of communication between activity and fragment, and what are their advantages and disadvantages? A common activity and fragment several communication methods 1 through handle in the activity to create a handle mechanism instance, and then in the creation of fragment through the construction method to pass the handle instance in the past, So fragment can send data to the activity. However, the following disadvantages are as follows: (1) The coupling between activity and fragment increases; (2) The results of activity processing cannot be fed back to fragment; (3) The memory leakage risk is increased; 2 The disadvantage of using the static variable is clearly increased memory consumption; 3 Use broadcasts to register broadcasts in activity and fragment, so that communication can be achieved. Its disadvantage: (1) Poor performance, delay, the user experience will be poor; (2) The general use of the standard broadcast, a send, multiple receivers, overqualified, poor performance; (3) Code redundancy, (4) Limited data transmission, 4 Eventbus, Rxbus (commonly known as universal oil) Its use method reference official documents, Its advantages are simple and convenient to use, its shortcomings are also obvious: (1) Eventbus, rxbus its internal uses is the reflection mechanism, then its performance will be reduced; (2) Code maintenance difficult (unfamiliar project code of the new person is difficult to find out how the implementation method is called), (3) Data return difficulties, They are one-way pass; 5 Ordinary interface write an interface in fragment, let activity to implement this interface, through this interface to bind activity and fragment together, so activity and fragment communicate in real time, In fact, Google is recommended to do so, because each fragment write an interface, will cause code redundancy, if fragment less good, more words, activity implementation of multiple interfaces, it appears that the activity head is very large, and the name of the interface is also a problem; Universal interface If the basis of the 5 can solve the code redundancy, interface naming, we know that a function includes function name, function body, parameters, return value, then you can build a simple framework to achieve the above problem.   Build None (have) parameters None (have) four class  &nbspAfter defining all the interface abstract classes, we define an interface management class that manages the invocation of the corresponding function method through the interface management class.

Finally, communication is implemented in the activity:

 Public classMainactivityextendsappcompatactivity{PrivateArraylist<fragment> fragmentarraylist =NewArraylist<>(); PrivateFragment mcurrentfragment; PrivateBottomnavigationbar Mbottomnavigationbar;    Badgeitem Badgeitem;    Fragmentmanager Mfragmentmanager; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main);    Initview (); }    Private voidInitview () {Mfragmentmanager=Getsupportfragmentmanager ();        Initfragemnt (); Showfragment (0); Mbottomnavigationbar=(Bottomnavigationbar) Findviewbyid (R.id.bottom_navigation_bar);        Mbottomnavigationbar.setmode (bottomnavigationbar.mode_fixed);        Mbottomnavigationbar.setbackgroundstyle (bottomnavigationbar.background_style_static); Mbottomnavigationbar.setbarbackgroundcolor (Android.        R.color.white); Badgeitem=NewBadgeitem (). SetBackgroundColor (color.red). SetText ("99"). Sethideonselect (true);//hide the corner mark when the setting is selectedMbottomnavigationbar. Setactivecolor (r.color.coloraccent)//Set the selected color. Setinactivecolor (R.color.colorprimary);//not selectedMbottomnavigationbar.additem (NewBottomnavigationitem (R.mipmap.ic_launcher, "Home"). AddItem (NewBottomnavigationitem (R.mipmap.ic_launcher, "Shop"). AddItem (NewBottomnavigationitem (r.mipmap.ic_launcher, "Shopping cart"). AddItem (NewBottomnavigationitem (R.mipmap.ic_launcher, "my"). Setbadgeitem (Badgeitem)). Initialise (); Mbottomnavigationbar.settabselectedlistener (NewBottomnavigationbar.ontabselectedlistener () {@Override Public voidOntabselected (intposition)            {showfragment (position); } @Override Public voidOntabunselected (intposition) {} @Override Public voidOntabreselected (intposition)    {            }        }); }    Private voidShowfragment (intpage) {fragmenttransaction mfragmenttransaction=Mfragmentmanager. BeginTransaction (); if(Mcurrentfragment! =NULL) {mfragmenttransaction.hide (mcurrentfragment); } mcurrentfragment=fragmentarraylist.get (page); if(mcurrentfragment.isadded ()) {mfragmenttransaction.show (mcurrentfragment); }Else{mfragmenttransaction.add (R.id.fragmenta, Mcurrentfragment,mcurrentfragment.getclass (). GetName ());    } mfragmenttransaction.commitallowingstateloss (); }    Private voidinitfragemnt () {Fragmentarraylist.add (NewA ()); Fragmentarraylist.add (NewB ()); Fragmentarraylist.add (NewC ()); Fragmentarraylist.add (NewD ()); }     Public voidSetfunctionforfragment (FinalString tag) {Basefragment Fragment=(basefragment) Mfragmentmanager.findfragmentbytag (tag); Functionmanager Functionmanager=functionmanager.getinstance (); Fragment.setmfunctionmanager (Functionmanager.addfunction (NewFunctionnoparamnotresult (A.INTERFCE) {@Override Public voidfunction () {Toast.maketext (mainactivity). This, "no parameter no return value" +Tag,toast.length_long). Show (); }}). addfunction (NewFunctionnoparamwithresult<string>(B.INTERFCE) {@Override PublicString function () {Toast.maketext (mainactivity. This, "No parameter has a return value", Toast.length_long). Show (); return"Zhang San"; }}). addfunction (NewFunctionwithparamnoresult<integer>(C.INTERFCE) {@Override Public voidfunction (Integer o) {toast.maketext (mainactivity. This, "parameter no return value" +O,toast.length_long). Show (); }}). addfunction (NewFunctionwithparamresultn<string>(D.INTERFCE) {@Override Publicstring function (String o) {toast.maketext (mainactivity. This, "with parameter return value" +O,toast.length_long). Show (); return"Zhangqie";    }        })); }}

SOURCE download GitHub:https://github.com/DickyQie/android-fragment-interface

Android--------Object-oriented universal interface for activity and fragment communication

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.