Encapsulation of reusable custom adapter, tribute to Xiang elder brother

Source: Internet
Author: User

look at the custom of Xiang Brother Almighty Adapter , I also take notes, analysis of the master of the way of thinking, let us into the inner world of the perverted programmer.

analysis of the almighty Adapter before, let's analyze the common Adapter

public class Reportspinneradapter extends Baseadapter {private context context;    Private list<string> str;        Public Reportspinneradapter (context context, list<string> str, int textWidth) {this.context = context;        This.str = str;    This.textwidth = TextWidth;    } @Override public int getcount () {return str.size ();    } @Override public Object getItem (int position) {return str.get (position);    } @Override public long getitemid (int position) {return position;        } @Override Public View GetView (int. position, View Convertview, ViewGroup parent) {Viewholder hold; if (convertview==null) {Convertview = Layoutinflater.from (context). Inflate (R.layout.spinner_layout,parent,false            );            hold = new Viewhold ();            Hold.textview = (TextView) Convertview.findviewbyid (R.id.textview);        Convertview.settag (hold); }else{hold = (viewhold) convertview.getTag ();        } hold.textView.setText (Str.get (position));    return convertview;    } static class viewholder{TextView TextView; }

Normal.Adapteris roughly divided into two points,GetViewand theViewholder, a class solves the problem and involves the reuse of the control, using theViewholder, the main logic is still inGetViewin, if this does not understand, you can first BaiduViewholder,GetViewthe logic in this is that ifConvertviewThe first time you are used, initialize the binding layout and set the tag, otherwise, fromConvertviewremovedViewholder, if you want to change the parameters of a control in a layout fromViewholderThe control setting parameter is removed because the controlConvertviewInitialization is initialized together, so setting parameters directly isOKup. This is a standard programmer's usual practice, however, so if we want to use it frequently in our programsAdapter, eachListvieworGridViewWe're going to get one.Adapter, wasted a lot of time, as a perverted programmer, Xiang elder brother how can endure, so out of such a blog Xiang elder brother blog, let us also can profit from, harvest new technology also harvested a fresh way of thinking.

summarize the custom universal Adapter , or is called a reusable Adapter , divided to see, is three points:

1. Package A special viewholder, you can pass in parameters directly get viewholder, take this step to kill:

if (convertview==null) {            Convertview = layoutinflater.from (context). Inflate (R.layout.spinner_layout,parent, FALSE);            hold = new Viewhold ();            Hold.textview = (TextView) Convertview.findviewbyid (R.id.textview);            Convertview.settag (hold);        } else{Hold            = (viewhold) Convertview.gettag ();}

to get rid of this step, it is necessary to think of what parameters to pass in order to directly Viewholder and that's the back of the few, 1. Layoutinflater.from (context) 2. R.layout.spinner_layout 3. Parent 4. Convertview

Know the conditions needed to say, directly write a

public class Viewholder {    private sparsearray<view> views;    Private View Convertview;    Public Viewholder (ViewGroup parent,layoutinflater inflater,int layoutid) {        this.views = new Sparsearray<view > ();        This.convertview = Inflater.inflate (layoutid,parent,false);        This.convertView.setTag (this);    }    /** *     Get viewholder     * @param parent     * @param convertview     * @param inflater     * @param layoutid     * @return     *    /public static Viewholder Getviewholder (ViewGroup parent,view convertview,layoutinflater Inflater,int layoutid) {        if (convertview==null) {            return new Viewholder (Parent,inflater,layoutid);        }        Return (Viewholder) Convertview.gettag ();    }

this sparsearray<view> views is actually a key-value pair that is used to save ListView or GridView all controls on each row or column are more efficient than hashmap, and the usage is

/**     * View     * @param viewId     * @param <T> * @return */public    <t extends view by ID >t getView (int viewId) {        View view = Views.get (viewId);        if (view==null) {            view = Convertview.findviewbyid (viewId);            Views.put (Viewid,view);        }        Return (T) view;    }

this way, a Viewholder it's done.

2. Write a general adapter, General Adapter, basically can not achieve, then what to do, do a semi-universal Adapter, since the semi-universal, is roughly the same, a few differences, the way to inherit the abstract class is the best

Public abstract class Commonadapter<t> extends Baseadapter {private list<t> List;    Private Layoutinflater Inflater;    private int layoutid;        Public Commonadapter (list<t> list, Context context,int layoutid) {this.list = list;        This.inflater = Layoutinflater.from (context);    This.layoutid = LayoutID;    } @Override public int getcount () {return list.size ();    } @Override public Object getItem (int position) {return list.get (position);    } @Override public long getitemid (int position) {return position; } @Override public View getView (int position, view Convertview, ViewGroup parent) {Viewholder Viewholder = V        Iewholder.getviewholder (Parent,convertview,inflater,layoutid);        Convert (viewholder,list.get (position));    return Viewholder.getconvertview (); } public abstract void convert (Viewholder viewholder,t T);}

First, we bind Adapter when you are unsure of the data source, you have to use a generic class and a generic collection, and then the incoming layout ID and the Context context, the need to assign a value to the control of the place to the abstract method, to subclass inheritance, so that after encapsulation, we need to do is less, only need to rewrite Convert methods and construction methods.

public class Myadapter extends commonadapter<bean> {public    myadapter (list<bean> List, context context, int LayoutID) {        super (list, context, LayoutID);    }    @Override public    void convert (Viewholder viewholder, bean Bean) {        ((TextView) Viewholder.getview (R.id.text) ). SetText ("This is test Data 1");        ((TextView) Viewholder.getview (R.id.text)). SetText ("This is test Data 1");}    }

in this way, you only need toActivityorFragmentto bind inMyadapter, the data and layoutIDand thecontentthe incoming is done. Just(Viewholder.getview (R.id.text)). SetTextThis kind of writing is very painful, the code in the word strong, but also to cut back the cursor, anyway, I personally is not accustomed to, then how to do it, can this, since we have aViewholderobject, let's change it.Viewholderobject, so that the public code a little more, we will repeat the place to write less. In theViewholderAdd the following method

/** * Get TextView * @return * */public TextView gettextview (int viewId) {return GetView (VIEWID) by ID; }/** * Get ImageView * @return * */public ImageView getimageview (int viewId) {return GetView (    VIEWID);    /** * Get button * @return * */Public button Getbutton (int viewId) {return GetView (VIEWID) based on ID) }/** * Get RadioButton * @return * */public RadioButton Getradiobutton (int viewId) {return GE    TView (VIEWID); }/** * Gets a CheckBox based on ID * @return */public CheckBox getcheckbox (int viewId) {return GetView (Viewi    D); /** * Get ImageButton * @return */public ImageButton Getimagebutton (int viewId) {return Getv by ID)    Iew (VIEWID); }/** * Get ImageButton * @return */public EditText getedittext (int viewId) {return GetView (vi    EWID); }

Well, our Myadapter in the Convert method can be written like this.

@Override public    void convert (Viewholder viewholder, bean Bean) {        Viewholder.gettextview (r.id.text). SetText ( "This is test Data 1");        Viewholder.gettextview (R.id.text). SetText ("This is test Data 2");    

so the writing will be a little smoother, compared with the hand, well, this basically is Xiang elder brother Almighty Custom Adapter The main content, the following diagram of the core ideas







Finally, Source: Click the Open link


Encapsulation of reusable custom adapter, tribute to Xiang elder brother

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.