Android ListView Universal Adapter Instance Code _android

Source: Internet
Author: User
Tags abstract stub xmlns

ListView is the most commonly used control in development, but it always writes repetitive code, wasting time without meaning.

Recent reference to some information, found a universal ListView adapter, less code, save time, summed up to share to everyone.

First there is a custom adapter inherited from Baseadapter, the following is a custom adapter, the essence of the GetView () method

Package com.example.mylistview.util;

Import java.util.List;
Import Android.content.Context;
Import Android.view.LayoutInflater;
Import Android.view.View;
Import Android.view.ViewGroup;

Import Android.widget.BaseAdapter;
 Public abstract class Commonadapter<t> extends Baseadapter {/** * contexts/private context mcontext;
 /** * Entity Class Collection * * Private list<t> Mdatas;
 Private Layoutinflater Minflater;

 /** * Control ID */private int mlayoutid;
  Public Commonadapter (context context, list<t> datas, int layoutid) {this.mcontext = context;
  This.mdatas = datas;
  This.mlayoutid = LayoutID;
 Minflater = Layoutinflater.from (context);
 @Override public int GetCount () {//TODO auto-generated a stub return mdatas.size ();
 @Override public T getitem (int arg0) {//TODO auto-generated Method Stub return Mdatas.get (ARG0);
 @Override public long Getitemid (int arg0) {//TODO auto-generated method stub return arg0; } @Override PublicView GetView (int arg0, view arg1, ViewGroup arg2) {//TODO auto-generated method stub Viewholder holder = Viewholder.
  Get (Mcontext, arg1, arg2, Mlayoutid, arg0);

  CONVERT (Holder, GetItem (arg0));
 return Holder.getconvertview ();
public abstract void Convert (Viewholder holder, T);

 }

The above abstract method, convert (Viewholder holder, T T), is equivalent to the previous generic code

Viewholder.mtextview = (TextView) convertview. Findviewbyid (R.id.id_tv_title);

ViewHolder.mTextView.setText (Bean.getname ());

Find the ID of the control and then go to the parameters in the duplicate code method such as facility SetText Viewholder holder, T-holder is equivalent to the viewholder,t in the previous generic code equivalent to a defined entity class bean.

A viewholder in the GetView () method in the above code needs to be declared by itself, following code and detailed comments:

Package com.example.mylistview.util;
Import Android.content.Context;
Import Android.graphics.Bitmap;
Import Android.renderscript.Type;
Import Android.util.SparseArray;
Import Android.view.LayoutInflater;
Import Android.view.View;
Import Android.view.ViewGroup;
Import Android.widget.ImageView;

Import Android.widget.TextView;
 public class Viewholder {/** * Sparsearray class store View set/private sparsearray<view> mviews;
 /** * * */private int mposition;

 /** * Layout File * * Private View Mconvertview;
 Public View Getconvertview () {return mconvertview; Public Viewholder (Context context, viewgroup parent, int layoutid, int position) {this.mviews = new sparsearray& Lt
  View> ();
  This.mposition = position;
  This.mconvertview = Layoutinflater.from (context). Inflate (LayoutID, parent, false);
 This.mConvertView.setTag (this); /** * Get a Viewholder Object * @param context * @param convertview * @param parent * @param layoutid * @param pos Ition * @retURN */public static Viewholder get (context context, View Convertview, viewgroup parent, int layoutid, int position)
  {if (null = = Convertview) {Return to New Viewholder (context, parent, layoutid, position);
   else {Viewholder holder = (viewholder) convertview.gettag ();
   Holder.mposition = position;
  return holder; /** * Gets the corresponding control through the ID of the control, and if not, add the views * @param viewid * @return/Public <t extends view> T getview (int

  Viewid) {View view = Mviews.get (Viewid);
   if (null = view) {view = Mconvertview.findviewbyid (Viewid);
  Mviews.put (Viewid, view);
 Return (T) view; /** * Set string for TextView * @param viewid * @param text * @return * * public viewholder setText (int viewid, Strin
  G text) {TextView TV = GetView (Viewid);
  Tv.settext (text);
 return this; /** * Set Picture for ImageView * * @param viewid * @param drawableid * @return * * Public viewholder Setimager esource (int viewid, int drawableid) {ImagevieW view = GetView (Viewid); 
  View.setimageresource (Drawableid); 
 return this; 
 public int getPosition () {return mposition;
 } 
}

Then write a adapter inherited from the universal adapter Commonadapter, or write a own adapter, because a project may have multiple ListView, but each item element, layout will be different, This tear is used to distinguish between different ListView and their own corresponding item. This amount of code is relatively small and can be written as an internal class in Activity.java.

Package com.example.mylistview.adapter;

Import java.util.List;
Import Android.content.Context;
Import Android.view.View;
Import Android.view.View.OnClickListener;

Import Android.widget.CheckBox;
Import COM.EXAMPLE.MYLISTVIEW.R;
Import Com.example.mylistview.domain.Bean;
Import Com.example.mylistview.util.CommonAdapter;

Import Com.example.mylistview.util.ViewHolder;  public class Myadapter extends commonadapter<bean> {public Myadapter (context context, list<bean> datas, int
  LayoutID) {Super (context, datas, LayoutID); TODO auto-generated Constructor stub} @Override public void convert (Viewholder holder, final bean bean) {//TOD
    O auto-generated Method Stub Holder.settext (R.id.tv_title, Bean.gettitle ()). SetText (R.id.tv_desc, Bean.getdesc ())
  . SetText (R.id.tv_time, Bean.gettime ()). SetText (R.id.tv_phone, Bean.getphone ());
  /** * Prevent CheckBox confusion * * Final checkbox Cbox = (CheckBox) (Holder.getview (R.ID.CB)); if (Cbox!= null) {Cbox.Setchecked (bean.ischecked ()); Cbox.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {Bean.setchecke
    D (cbox.ischecked ());
  }
   });

 }
 }

}

After optimization, the adapter is much simpler. The following are the code in the entity class, item, and Mainactivity.java:

Entity classes:

Package com.example.mylistview.domain;
 public class Bean {private String title;
 Private String desc;
 Private String time;
 Private String phone;

 Private Boolean ischecked;
 public Boolean ischecked () {return ischecked;
 } public void Setchecked (Boolean ischecked) {this.ischecked = ischecked; /** * @param title * @param desc * @param time * @param phone/public Bean (string title, String desc, Str
  ing time, String phone) {this.title = title;
  THIS.DESC = desc;
  This.time = time;
 This.phone = phone;
 Public String GetTitle () {return title;
 public void Settitle (String title) {this.title = title;
 Public String GetDesc () {return desc;
 } public void Setdesc (String desc) {THIS.DESC = desc;
 Public String GetTime () {return time;
 public void SetTime (String time) {this.time = time;
 Public String Getphone () {return phone;
 public void Setphone (String phone) {this.phone = phone;

 }

}

Mainactivity.java:

Key code:

Parameters have context, collection, and their corresponding item on it
adapter = new Myadapter (this, Mdatas, R.layout.item);

Package com.example.mylistview.ui;
Import java.util.ArrayList;

Import java.util.List;
Import android.app.Activity;
Import android.content.Intent;
Import Android.os.Bundle;
Import Android.view.View;
Import Android.widget.AdapterView;
Import Android.widget.AdapterView.OnItemClickListener;

Import Android.widget.ListView;
Import COM.EXAMPLE.MYLISTVIEW.R;
Import Com.example.mylistview.adapter.MyAdapter;

Import Com.example.mylistview.domain.Bean;
 public class Mainactivity extends activity {private ListView ListView;
 Private list<bean> Mdatas;

 /** * Adapter * * Private Myadapter adapter;
  @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
  Setcontentview (R.layout.activity_main);
  Initview ();
  InitData ();
 Listener (); private void Listener () {//TODO auto-generated Method Stub Listview.setonitemclicklistener (new Onitemclicklisten ER () {@Override public void Onitemclick (adapterview<?> arg0, View arg1,int arg2, long arg3) {//TODO auto-generated Method Stub startactivity (new Intent (Mainactivity.this, Seconda
   Ctivity.class));
 }
  });
  private void InitData () {//TODO auto-generated method Stub mdatas = new Arraylist<bean> ();
  Bean bean = new Bean ("Android skill get", "android-build omnipotent ListView and GridView Adapter", "2015-08-05", "10086");
  Mdatas.add (Bean);
  Bean = new Bean ("Pick up Kangzhirong One", "Pick up Kangzhirong in Starbucks", "2015-08-06", "10086");
  Mdatas.add (Bean);
  Bean = new Bean ("GetTop One", "pick up top one in Korea Seoul", "2015-08-07", "10086");
 
  Mdatas.add (Bean);
  adapter = new Myadapter (this, Mdatas, R.layout.item);
  
 Listview.setadapter (adapter);
 private void Initview () {//TODO auto-generated method Stub listView = (ListView) Findviewbyid (R.id.listview);

 }

}

Item Layout:

<?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=" wrap_content "android:padding=" 10DP "> < CheckBox android:focusable= "false" android:id= "@+id/cb" android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" android:layout_alignparentright= "true" android:layout_centerinparent= "true"/> <TextView Andr Oid:id= "@+id/tv_title" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Android:layout_ margintop= "10DP" android:singleline= "true" android:text= "Android new skill get"/> <textview android:id= "@+id/tv_de" SC "android:layout_width=" match_parent "android:layout_height=" wrap_content "android:layout_below=" @id/tv_title "a ndroid:layout_margintop= "10DP" android:layout_toleftof= "@id/cb" android:maxlines= "2" android:text= " android-Build omnipotent ListView and GridView Adapter "android:textcolor="#898989 "/> <textview android:id=" @+id/tv_time "android:layout_width=" Wrap_content "android:layout_height=" W Rap_content "android:layout_below=" @id/tv_desc "android:layout_margintop=" 10DP "android:text=" 2015-08-05 "Android: Textcolor= "#898989" android:textsize= "12sp"/> <textview android:id= "@+id/tv_phone" android:layout_width= "WR" Ap_content "android:layout_height=" Wrap_content "android:layout_alignparentright=" true "android:layout_below=" @id
  /tv_desc "android:layout_margintop=" 10DP "android:background=" #20793D "android:maxlines=" 1 "android:text=" 10086 "

 android:padding= "4DP" android:textcolor= "#FFF"/> </RelativeLayout>

Effect Chart:

Use this to fit another different layout:

The new layout of the adapter like inherit their own omnipotent Adapter:commonadapter

Package com.example.mylistview.adapter;

Import java.util.List;
Import Java.util.Map;


Import Android.content.Context;

Import COM.EXAMPLE.MYLISTVIEW.R;
Import Com.example.mylistview.util.CommonAdapter;
Import Com.example.mylistview.util.ViewHolder;

public class Secondadapter extends Commonadapter<map<string, string>> {public

 secondadapter (context Context, list<map<string, string>> datas,
   int layoutid) {
  Super (context, datas, layoutid);
  TODO auto-generated constructor stub
 }

 @Override public
 void convert (Viewholder holder, map< String, string> t) {
  //TODO auto-generated method Stub
  holder.settext (R.id.tv_item2values, T.get ("values "));
 }

}

Activity.java Code:

Package com.example.mylistview.ui;
Import java.util.ArrayList;
Import Java.util.HashMap;
Import java.util.List;

Import Java.util.Map;
Import android.app.Activity;
Import Android.os.Bundle;

Import Android.widget.ListView;
Import COM.EXAMPLE.MYLISTVIEW.R;
Import Com.example.mylistview.adapter.MyAdapter;

Import Com.example.mylistview.adapter.SecondAdapter;
 public class Secondactivity extends activity {private ListView listview_second;
 Private Secondadapter Secondadapter;

 Private list<map<string, string>> lists = new arraylist<map<string, string>> ();
  @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
  Setcontentview (R.layout.activity_second);
  Initview ();
 InitData (); private void InitData () {//TODO auto-generated method stub for (int i = 0; i < 4; i++) {Map map = new has
   Hmap<string, string> ();
   Map.put ("Values", "entries" + i);
  Lists.add (map); } secondadapter = new SecondadApter (this, lists, r.layout.item2);
 Listview_second.setadapter (Secondadapter); private void Initview () {//TODO auto-generated method Stub listview_second = (ListView) Findviewbyid (R.ID.LISTVI
 Ew_second);

 }

}

Item

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android=
"http://schemas.android.com/apk/" Res/android "
 android:layout_width=" match_parent "
 android:layout_height=" match_parent "
 android:o" rientation= "Horizontal" >

 

 <textview
  android:id= "@+id/tv_item2values"
  Wrap_content "
  android:layout_height=" wrap_content "
  android:layout_gravity=" center "
  android:text= "FFFFFF"
  android:layout_margin= "16DP"
  android:gravity= "center"/>

</LinearLayout>

Effect Chart:

The above is to the Android ListView data collation, hope to bring help to everyone!

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.