Adapter mode for Android design mode

Source: Internet
Author: User

first, the role

Adapter mode (Adapter): The interface of one class is converted into another interface that the customer wants, so that those classes that are incompatible with the interface and cannot work together can work together without having to change the original class or interface.

Second, the application scenario

1. The interface of the business is incompatible with the class of work (e.g., some methods of implementing the interface are missing from the class) but need to work together

2. Provide interfaces for new business requirements based on existing interfaces and classes

Three, the common use way

In the case of USB and phone handsets, suppose the phone class is designed with the call (), SMS (), Takealong () attribute method, and the store (), Takealong () behavior is defined when designing the USB interface. If there are new business requirements, need to generate Xiaomi phone class with phone class and USB interface features, assuming that the phone class and USB interface has been put into use in business, it is clear that to modify the method and interface in the original class behavior to meet the new business requirements is not advisable, Now the adapter model comes in handy.

There are two main types of adapter modes: Class adaptation mode and object adaptation mode

1. Class Adaptation mode

The general meaning is that the new business class Xiaomi by inheriting the class phone of the old business and implementing interface USB to meet the new business of an adaptation.

The code is as follows:

USB Interface Class

Public   usb{    store(); Takealong ();}      
Phone class

Public classPhone {Public voidPager() {System. out. Print ("Phone can call");    }Public voidSMS() {System. out. Print ("Phone can send messages");    }Public voidTakealong() {System. out. println ("Phone Takealong");    }}
The Xiaomi class after fitting

usb{    Store() {        System.  out. println ("store implements USB");     }}
After the adaptation is complete, you can use the Xiaomi class to complete some functions

XiaomiXiaomi(); Xm.takealong (); Xm.store (); Xm.call ();
2. Object Adaptation mode

The way of implementation is very simple, in fact, when the adaptation of the old business phone as a new adaptation class (Xiaomiwrapper) A member object to deal with, and then the appropriate class only need to implement interface USB.

Public classXiaomiwrapperImplementsusb{/*** 1.Create aWrapperclass, holding an instance of the original class,     * 2.in theWrapperMethod of the class, the method that invokes the instance is the line     */    PrivatePhonePhone; PublicXiaomiwrapper (phone phone) { This.Phone= Phone;    }@Override    Public voidStore() {            }@Override    Public voidTakealong() {Phone. Takealong ();    }}
Once the adaptation is complete, the original object is passed in by the constructor function.

Xiaomiwrapperxiaomiwrapper(Phone ()); Xiaomiwrapper.store (); Xiaomiwrapper.takealong ();
The best use of the adapter mode in Android source code is to use adapter to display the data in the ListView.

The code omits the ListView Mylistview = (ListView) Findviewbyid (listview_id); Set Adapter Mylistview.setadapter (new Myadapter (context, mydatas));
Adapter class//Adapter publicclass Myadapter extends Baseadapter{Private Layoutinflater minflater;         List<string> Mdatas;            Public Myadapter (context context, list<string> datas) {this.minflater = Layoutinflater.from (context);        Mdatas = datas;        } @Override public int getcount () {return mdatas.size ();        } @Override public String getItem (int pos) {return mdatas.get (POS);        } @Override public long getitemid (int pos) {return pos; }//parsing, setting, caching Convertview and related content @Override public View getView (int position, view Convertview, Viewgrou            P parent) {Viewholder holder = null;                  The reuse if of Item view (Convertview = = null) {holder = new Viewholder ();                Convertview = minflater.inflate (R.layout.my_listview_item, NULL);               Get title Holder.title = (TextView) Convertview.findviewbyid (r.id.title); Convertview.settag (holder);            } else {holder = (Viewholder) convertview.gettag ();            } holder.title.setText (Mdatas.get (position));        return convertview; }    }
So how does the ListView work with adapter mode (more than adapter mode)?

ListView inherits from Abslistview,adapter definition in Abslistview, let's take a look at this class.

public abstractclass Abslistview extends Adapterview<ListAdapter>Implements Textwatcher,Viewtreeobserver.Ongloballayoutlistener,Filter.Filterlistener,Viewtreeobserver.Ontouchmodechangelistener,Remoteviewsadapter.Remoteadapterconnectioncallback {ListAdapter madapter;        function called when associated to window @Override protected void Onattachedtowindow () {Super.onattachedtowindow ();        Code omitted//To register an observer with the adapter, this mode is described in the next article.            if (madapter! = null && Mdatasetobserver = = null) {Mdatasetobserver = new adapterdatasetobserver ();            Madapter.registerdatasetobserver (Mdatasetobserver); Data may be changed while we were detached.            Refresh.            Mdatachanged = true;        Molditemcount = Mitemcount//Gets the number of item, calls the GetCount method of Madapter Mitemcount = Madapter.getcount ();    } misattached = true; The/** * Subclass needs to overwrite the Layoutchildren () function to lay out the child view, which is the item view/@Override protected void OnLayout (Boolean cha        nged, int l, int t, int r, int b) {super.onlayout (changed, L, T, R, b);        Minlayout = true;            if (changed) {int childCount = Getchildcount ();      for (int i = 0; i < ChildCount; i++) {          Getchildat (i). Forcelayout ();        } mrecycler.markchildrendirty (); } if (Mfastscroller = null && mitemcount! = molditemcount) {mfastscroller.onitemcountchanged (M        Olditemcount, Mitemcount);        }//Layout child View Layoutchildren ();        Minlayout = false;    Moverscrollmax = (b-t)/overscroll_limit_divisor;        }//Get an Item View view Obtainview (int position, boolean[] isscrap) {isscrap[0] = false;        View Scrapview;        Retrieved from the cached item view, the reuse mechanism of the ListView is here Scrapview = Mrecycler.getscrapview (position);        View child;            if (Scrapview! = null) {//code omit child = Madapter.getview (position, Scrapview, this);            Code omitted} else {child = Madapter.getview (position, NULL, this);    Code omitted} return child; }    }
Abslistview defines the frame of the collection view, such as the application of the adapter pattern, the logic for reusing the item view, the layout of the item view logic, and so on. Subclasses only need to override specific methods to implement the functions of a collection view, such as a ListView.

The related method in the ListView.

protected void Layoutchildren () {//code omitted try {Super.layoutchildren ();            Invalidate ();                Code omitted//layout according to layout mode item View switch (mlayoutmode) {case layout_set_selection:                if (Newsel! = null) {sel = Fillfromselection (Newsel.gettop (), Childrentop, Childrenbottom);                } else {sel = Fillfrommiddle (Childrentop, Childrenbottom);            } break;                Case Layout_sync:sel = fillspecific (msyncposition, mspecifictop);            Break                Case Layout_force_bottom:sel = fillUp (mItemCount-1, Childrenbottom);                Adjustviewsupordown ();            Break                Case layout_force_top:mfirstposition = 0;                sel = Fillfromtop (childrentop);                Adjustviewsupordown ();            Break             Case LAYOUT_SPECIFIC:   sel = fillspecific (Reconcileselectedposition (), mspecifictop);            Break                Case Layout_move_selection:sel = moveselection (Oldsel, Newsel, Delta, Childrentop, Childrenbottom);            Break            Default://code omitted break; }}//Fill in item View from top to bottom [just one of the fill methods] private view FillDown (int pos, int nexttop) {View Selectedview = n        Ull        int end = (mbottom-mtop);        if ((Mgroupflags & clip_to_padding_mask) = = Clip_to_padding_mask) {end-= Mlistpadding.bottom;            } while (Nexttop < end && Pos < Mitemcount) {//are this selected item?            Boolean selected = pos = = mselectedposition;            View child = Makeandaddview (pos, Nexttop, True, Mlistpadding.left, selected);            Nexttop = Child.getbottom () + mdividerheight;            if (selected) {Selectedview = child; } POs++;    } return Selectedview;  }//Add Item View private view Makeandaddview (int position, int y, boolean flow, int Childrenleft, Boolean        Selected) {View child; Code omitted//Make a new view for this position, or convert an unused view if possible child = Obtainview (posi        tion, misscrap); This needs to is positioned and measured setupchild (child, position, y, Flow, Childrenleft, selected, misscrap[0        ]);    return child; }
The ListView Abslistview the Layoutchilden function in the function, where the item View is laid out according to the layout pattern. The number and style of item view are obtained by adapter corresponding method, get the number, item view, the item view layout to the corresponding coordinates of the ListView, plus the reuse mechanism of item view, The whole ListView is basically working.

Benefits of Adapter Mode*Better reusability
The system needs to use the existing classes, and the interfaces of this class do not meet the needs of the system. The adapter mode allows for better reuse of these features.

* Improved scalability
When implementing the adapter functionality, you can invoke the features you have developed to naturally extend the functionality of the system.

Adapter mode of the shortcomings of the use of the adapter, will make the system very messy, not easy to grasp the overall. For example, clearly see the call is a interface, in fact, the interior is adapted to the implementation of the B interface, a system if too many occurrences of this situation, is tantamount to a disaster. So if it's not necessary, you can refactor the system without using the adapter.

This article references: http://www.codeceo.com/article/android-listview-adapter-2.html

Adapter mode for Android design mode

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.