Android to create a universal adapter (RPM)

Source: Internet
Author: User

Deserted for two days, today to share with you a ListView adapter

In the previous period of time in the Learning Network video, feel this way to achieve better, it is recorded down, the recent project has been used several times, saving a lot of code, hereby take to share with you.

Or look at the picture first, here I imitate the blog Park app's list style made a static data list

The analogy here is more, but the core of only two, the rest are used for demonstration, first look at the core of the two classes

Viewholderm.java

Package Landptf.tools;import Android.content.context;import Android.text.spanned;import Android.util.SparseArray; Import Android.view.layoutinflater;import Android.view.view;import Android.view.viewgroup;import Android.widget.imageview;import android.widget.textview;/** * @author LANDPTF * Public Viewholder */public Class    viewholderm {private sparsearray<view> viewarray;    private int position;    Private View Mconvertview;    Private Object tag; /** * Construction Method * @param context * @param convertview * @param parent * @param layoutid * @param posit Ion */Public viewholderm (context context, View Convertview, viewgroup parent, int layoutid, int positio        N) {this.position = position;        Use Sparsearray high efficiency some viewarray = new sparsearray<view> ();        Load Layout Mconvertview = Layoutinflater.from (context). Inflate (LayoutID, parent,false);    Assigns the viewholderm to the view's tag mconvertview.settag (this); } publicStatic Viewholderm Get (context context, View Convertview, viewgroup parent, int layoutid, int position) { if (Convertview = = null) {//If Convertview is empty, instantiate Viewholderm return new Viewholderm (context, Conve        Rtview, parent, layoutid,position); } else {//otherwise remove viewholderm from Convertview's tag to avoid duplicate creation of viewholderm holder = (viewholderm) convertview.g            Ettag ();            Holder.position = position;        return holder;    }} public View Getconvertview () {return mconvertview;    } public Object Gettag () {return tag;    } public void Settag (Object tag) {This.tag = tag;    } public int getPosition () {return position;    } public void SetPosition (int position) {this.position = position; /** * Get Control object through ViewId * @param viewId * @return */@SuppressWarnings ("unchecked") public <t E Xtends view> T getView (int viewId) {View view = Viewarray.get (viewId);            if (view = = null) {view = Mconvertview.findviewbyid (viewId);        Viewarray.put (viewId, view);    } return (T) view; }/**------------------------------------Gorgeous split line------------------------------------*//** The following methods for the additional encapsulation method, just a few , you can gradually improve * * */** * Set textview content * @param viewId * @param text * @return */Public viewho        Lderm setText (int viewId, String text) {TextView TV = GetView (viewId);        Tv.settext (text);    return this; }/** * Set contents of TextView * @param viewId * @param text,spanned type, you can set some font discoloration * @return */Public        Viewholderm setText (int viewId, spanned text) {TextView TV = GetView (viewId);        Tv.settext (text);    return this; /** * Set the visibility of the picture * @param viewId * @param visible * @return */public viewholderm Setimagevi ewvisible (int viewId, Boolean visible) {ImageView IV = GetView(VIEWID);        if (visible) {iv.setvisibility (view.visible);        }else {iv.setvisibility (view.gone);    } return this; }}

2 Adapterm.java

Package Landptf.tools;import Java.util.list;import Android.content.context;import android.view.view;import Android.view.viewgroup;import android.widget.baseadapter;/** * @author LANDPTF * Public Adapter list Adapter */public abstract    Class Adapterm<t> extends Baseadapter {private context context; To enrich the program functionality, two common data types are available private list<t> dataList = null;//data source list<t> private t[] DataArray = null;//data source t[        ]//Layout file ID private int layoutid; /** * Construction Method * @param context * @param layoutid * @param dataList */Public adapterm (context context,        int LayoutID, list<t> dataList) {this.context = context;        This.datalist = dataList;    This.layoutid = LayoutID; }/** * Constructed method (different from previous only data source) * @param context * @param layoutid * @param dataarray */Public Ad        Apterm (Context Context,int LayoutID, t[] dataarray) {this.context = context;        This.dataarray = DataArray; This.layoutid = LayOutid;        } @Override public int getcount () {if (dataList! = null) {return datalist.size ();        }else {return dataarray.length; }} @Override public T getItem (int position) {if (dataList! = null) {return Datalist.get (posi        tion);        }else {return dataarray[position];    }} @Override public long getitemid (int position) {return position; } @Override public View getView (int position, view Convertview, ViewGroup parent) {Viewholderm Holder =        New Viewholderm (context, Convertview, parent,layoutid, position);        Convert (Holder,getitem (position));    return Holder.getconvertview (); }/** * The abstract method to be implemented * @param holder * @param model * */public abstract void convert (Viewholderm holder, T model);}

Next look at the layout file, a total of two is the activity of the page, a list of items
Activity_list.xml

<?xml version= "1.0" encoding= "Utf-8"? ><relativelayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" match_parent "    android:layout_height=" Match_parent "    android: background= "#EFEFEF" >         <include android:id= "@+id/title" layout= "@layout/child_titlebarm"/>          < ListView          android:id= "@+id/lv_list"         android:layout_width= "match_parent"         android:layout_height= " Match_parent "         android:layout_below=" @+id/title "         android:layout_margintop=" 10DP "         android: Background= "@android: Color/white"         android:divider= "#A9A9A9"          android:dividerheight= "1DP" >     </ListView></RelativeLayout>

Item_messgae.xml

<?xml version= "1.0" encoding= "Utf-8"? ><relativelayout xmlns:android= "http://schemas.android.com/apk/res/ Android "xmlns:tools=" Http://schemas.android.com/tools "android:layout_width=" Match_parent "android:layout_height = "Wrap_content" tools:ignore= "Hardcodedtext" > <textview android:id= "@+id/tv_title" Android:layo Ut_width= "Match_parent" android:layout_height= "wrap_content" android:layout_marginleft= "10DP" Android : layout_marginright= "10DP" android:layout_margintop= "10DP" android:maxlines= "2" android:textcolor= "#6 96969 "android:textsize=" 20sp "/> <textview android:id=" @+id/tv_content "Android:layout_widt H= "Match_parent" android:layout_height= "wrap_content" android:layout_alignleft= "@+id/tv_title" Androi d:layout_below= "@+id/tv_title" android:layout_marginright= "10DP" android:layout_margintop= "10DP" Android oid:maxlines= "3" android:tExtcolor= "#696969" android:textsize= "16sp"/> <textview android:id= "@+id/tv_comment" Android         : layout_width= "wrap_content" android:layout_height= "wrap_content" android:layout_alignleft= "@+id/tv_content"        android:layout_below= "@+id/tv_content" android:layout_margintop= "10DP" android:textcolor= "#696969" Android:textsize= "18sp"/> <textview android:id= "@+id/tv_read" android:layout_width= "Wrap_con Tent "android:layout_height=" Wrap_content "android:layout_aligntop=" @+id/tv_comment "Android:layout_c Enterhorizontal= "true" android:textcolor= "#696969" android:textsize= "18sp"/> <textview Android Oid:id= "@+id/tv_collect" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" and         roid:layout_aligntop= "@+id/tv_read" android:layout_alignparentright= "true" android:layout_marginright= "10DP" Android:text= "immediatelyBookmark "android:textcolor=" #696969 "android:textsize=" 18SP "/></relativelayout> 

Next we define a adapter class inheritance Adapterm,listadapter.java

Package Landptf.test;import Landptf.control.r;import Android.content.context;import landptf.tools.adapterm;import landptf.tools.viewholderm;/** * @author LANDPTF * ListAdapter List Adapter */public class ListAdapter extends Adapterm<mess agebean>{Public    ListAdapter (context context, int layoutid, messagebean[] dataarray) {        Super (context, LayoutID, DataArray);    }    @Override public    void convert (viewholderm holder, Messagebean model) {        //For a control bound content        Holder.settext (r.id.tv _title, Model.gettitle ());        Holder.settext (R.id.tv_content, Model.getcontent ());        Holder.settext (R.id.tv_comment, model.getcomment () + "comment");        Holder.settext (R.id.tv_read, Model.getread () + "read");}    }

And finally the activity class, Listactivity.java.

Package Landptf.test;import Landptf.control.r;import Landptf.control.titlebarm;import android.app.Activity;import Android.os.bundle;import android.widget.listview;/** * @author LANDPTF * List Adapter test Classes */public class Listactivity extends A    ctivity{///Here used before the custom title bar//If interested can look at my previous blog, otherwise ignored can be private titlebarm tbtitle;    ListView Object Private ListView Lvlist;    Custom adapter Private ListAdapter ListAdapter;    Data source entity, here with an array as an example, you can also choose to use list as the data source private messagebean[] Msgarray;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (r.layout.activity_list);    Initview ();        } private void Initview () {tbtitle = (titlebarm) Findviewbyid (r.id.tbm_title);        Tbtitle.settitletext ("Build a Universal adapter");        InitData ();        Lvlist = (ListView) Findviewbyid (r.id.lv_list);        ListAdapter = new ListAdapter (this, r.layout.item_message, Msgarray);   Lvlist.setadapter (ListAdapter); }//Load Data private void InitData () {Msgarray = new messagebean[10]; Msgarray[0] = new Messagebean ("Android Custom title bar", "see today how to implement a custom title bar by combining multiple controls It is well known that the title bar is an essential control in the application, and in order to avoid multiple rewrites, wrap it up, Can be called for each layout.        Here we use the classic left and right layout, can also be adjusted according to the needs of the project, such as the right to add a control, or the title left can note: which applies to the previous article in the Buttonm control, you can ", 0, 273); MSGARRAY[1] = new Messagebean ("Android custom control, dynamically set button style", "see today a dynamic implementation of some effects by overriding the button, such as rounded rectangles, circles, changing the font by pressing, changing the background color,        Change the background map and so on, this implementation is absolutely not unique, and through the XML file can be easily implemented, just to make the control style completely code implementation, more convenient packaging to apply to other projects look at the following: Figure 1 initial state Figure 2 Press the first ", 0, 400); MSGARRAY[2] = new Messagebean ("Android custom control implementation TextView The font color changes after pressing", "today to share with you the Android custom control to get started, first introduced a simple effect textview, Press to change the color of the font, later slowly expand more powerful function directly to see the picture the first is to press the next section of the diagram, the function is very simple, it is easy to implement, see how to rewrite TextView to achieve a total of three files Textviewm.java,mainactivit ", 0,        202); MSGARRAY[3] = new Messagebean ("Android Custom title bar", "see today how to implement a custom title bar by combining multiple controls It is well known that the title bar is an essential control in the application, and in order to avoid multiple rewrites, wrap it up, Can be called for each layout.        Here we use the classic left and right layout, can also be adjusted according to the needs of the project, such as the right to add a control, or the title left can note: which applies to the previous article in the Buttonm control, you can ", 0, 273); MSGARRAY[4] =New Messagebean ("Android custom control, dynamically set button style", "see today a dynamic implementation of some effects by overriding the button, such as rounded rectangles, circles, pressed to change the font, change the background color, change the background map, etc. here to illustrate,        This implementation is absolutely not unique, and through the XML file can be easily implemented, just to make the control style completely code implementation, more convenient packaging to apply to other projects look at the following: Figure 1 initial state Figure 2 Press the first ", 0, 400); MSGARRAY[5] = new Messagebean ("Android custom control implementation TextView The font color changes after pressing", "today to share with you the Android custom control to get started, first introduced a simple effect textview, Press to change the color of the font, later slowly expand more powerful function directly to see the picture the first is to press the next section of the diagram, the function is very simple, it is easy to implement, see how to rewrite TextView to achieve a total of three files Textviewm.java,mainactivit ", 0,        202); MSGARRAY[6] = new Messagebean ("Android Custom title bar", "see today how to implement a custom title bar by combining multiple controls It is well known that the title bar is an essential control in the application, and in order to avoid multiple rewrites, wrap it up, Can be called for each layout.        Here we use the classic left and right layout, can also be adjusted according to the needs of the project, such as the right to add a control, or the title left can note: which applies to the previous article in the Buttonm control, you can ", 0, 273); MSGARRAY[7] = new Messagebean ("Android custom control, dynamically set button style", "see today a dynamic implementation of some effects by overriding the button, such as rounded rectangles, circles, changing the font by pressing, changing the background color,        Change the background map and so on, this implementation is absolutely not unique, and through the XML file can be easily implemented, just to make the control style completely code implementation, more convenient packaging to apply to other projects look at the following: Figure 1 initial state Figure 2 Press the first ", 0, 400); MSGARRAY[8] = new Messagebean ("Android custom control implements TextView font color change after Press", "to share with you today the introduction of Android custom controls, first introduce a simple effect textvieW, press change font color, later slowly expand more powerful function directly see the picture the first is to press the next section of the diagram, the function is very simple, it is easy to implement, see how to rewrite TextView to achieve a total of three files Textviewm.java,mainactivit ", 0        , 202); MSGARRAY[9] = new Messagebean ("Android Custom title bar", "see today how to implement a custom title bar by combining multiple controls It is well known that the title bar is an essential control in the application, and in order to avoid multiple rewrites, wrap it up, Can be called for each layout.    Here we use the classic left and right layout, can also be adjusted according to the needs of the project, such as the right to add a control, or the title left can note: which applies to the previous article in the Buttonm control, you can ", 0, 273); }}

The above is all the code, so that later add other ListView do not need to define a adapter, a viewholder, the above listadapter can also not need, directly in the activity to implement the definition adapterm can be, However, some complex list items are also recommended to customize a adapter to inherit adapterm.

Finally, the spirit of the Internet open, sharing, the original video address is attached to http://www.imooc.com/learn/372, personal comparison like Mu class network.

Android to create a universal adapter (RPM)

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.