ListView Custom Adapter encapsulation in Android development _android

Source: Internet
Author: User
Tags rar

"Introduction"

The order in which we usually write ListView is this:
• Data sets that need to be displayed list<t>
• Write a ListView for this dataset
• Write a adapter for this listview, usually inherited from Baseadapter
• Write a Viewholder class inside the baseadapter, corresponding to the item control inside the ListView, to improve the query efficiency of the control

Analysis:

List<t>:listview--> Adapter extends Baseadapter-->

In general, a ListView corresponds to a adapter class, corresponding to a Viewholder class, then if there are 20 ListView in an app, do we have to write 20 times? So the practice is:
• Extract Viewholder as a common class.
• Encapsulate adapter into Commonadapter as a common class.

first, the traditional way to write adapters:

(1) Activity_main.xml:

<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=" Match_parent " >

<listview
 android:id= "@+id/listview"
 android:layout_width= "Match_parent"
 android: layout_height= "Match_parent" ></ListView>

</RelativeLayout>

(2) Item_listview.xml: Layout file for individual item

<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=" Match_parent "Android: padding= "10DP" > <textview android:id= "@+id/titletv" android:layout_width= "Wrap_content" Android:layout_ height= "Wrap_content" android:singleline= "true" android:text= "new Android Skills" android:textcolor= "#444" Android: Textsize= "16sp"/> <textview android:id= "@+id/desctv" android:layout_width= "Match_parent" Android:layout_
 height= "Wrap_content" android:layout_below= "@+id/titletv" android:layout_margintop= "10DP" android:maxLines= "2" android:minlines= "1" android:text= "Android creates universal adapters for ListView and GridView" Android:textcolor= "#898989" android:textsize = "16sp"/> <textview android:id= "@+id/timetv" android:paddingtop= "3DP" android:layout_width= "Wrap_content" and roid:layout_height= "Wrap_content" android:layout_below= "@+id/desctv" android:layout_margintop= "10DP" android:text= "2015-05-04" android:textcolor= "#898989" android:textsize= "12sp"/> <textview android:pad ding= "2DP" android:id= "@+id/phonetv" android:gravity= "center" android:layout_width= "Wrap_content" Android:layout_ height= "Wrap_content" android:layout_below= "@+id/desctv" android:layout_margintop= "10DP" android:background= "# 2ed667 "android:drawableleft=" @mipmap/phone "android:drawablepadding=" 5DP "android:text=" 10086 "android:textColor="
 "#ffffff" android:textsize= "12SP" android:layout_alignparentright= "true"/> </RelativeLayout>

Its corresponding layout effect is as follows:

(3) Bean.java:ListView data set

Package com.smyhvae.baseadapter.entities;

/**
 * Created by smyhvae on 2015/5/4.
 * * Public
class Bean {
 private String title;
 Private String desc;
 Private String time;
 Private String phone;

 Public beans () {
 } public

 Beans (string title, String desc, string 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;
 }
}

(4) Myadapter.java: Custom Adapter, inherited from baseadapter 

Package com.smyhvae.baseadapter;
Import Android.content.Context;
Import Android.view.LayoutInflater;
Import Android.view.View;
Import Android.view.ViewGroup;
Import Android.widget.BaseAdapter;

Import Android.widget.TextView;

Import Com.smyhvae.baseadapter.entities.Bean;

Import java.util.List;
 /** * Created by smyhvae on 2015/5/4.
 * * public class Myadapter extends Baseadapter {private Layoutinflater minflater;

 Private list<bean> Mdatas; Myadapter needs a context, gets layout.inflater through the context, and then loads the item's layout by inflater the public myadapter (context, list<
 Bean> datas) {minflater = Layoutinflater.from (context);
 Mdatas = datas;
 //Returns the length of the dataset @Override public int GetCount () {return mdatas.size ();
 @Override public Object getitem (int position) {return mdatas.get (position);
 @Override public long getitemid (int position) {return position; }//This method is the focus, we want to write a viewholder @Override public View getview (int position, View Convertview, ViewGroup parent) {Viewholder holder = null;  if (Convertview = = null) {Convertview = Minflater.inflate (R.layout.item_listview, parent, false);//load Layout holder = new

  Viewholder ();
  Holder.titletv = (TextView) Convertview.findviewbyid (R.ID.TITLETV);
  HOLDER.DESCTV = (TextView) Convertview.findviewbyid (R.ID.DESCTV);
  Holder.timetv = (TextView) Convertview.findviewbyid (R.ID.TIMETV);

  Holder.phonetv = (TextView) Convertview.findviewbyid (R.ID.PHONETV);
 Convertview.settag (holder);
 else {//else Inside the description, Convertview has been reused, the Convertview has been set in the tag, that is, holder holder = (viewholder) convertview.gettag ();
 The Bean bean = mdatas.get (position);
 Holder.titleTv.setText (Bean.gettitle ());
 Holder.descTv.setText (Bean.getdesc ());
 Holder.timeTv.setText (Bean.gettime ());

 Holder.phoneTv.setText (Bean.getphone ());
 return convertview; }//This viewholder can only serve the current specific adapter, because the control of the item will be specified in Viewholder, different listview,item may be different, so Viewholder is written as a proprietary class private
 Class Viewholder {TextView Titletv;
 TextView DESCTV; TextView TiMeTV;
 TextView Phonetv;
 }

}

(5) mainactivity.java: 

Package com.smyhvae.baseadapter;
Import android.app.Activity;
Import Android.os.Bundle;
Import Android.view.Menu;
Import Android.view.MenuItem;

Import Android.widget.ListView;

Import Com.smyhvae.baseadapter.entities.Bean;
Import java.util.ArrayList;

Import java.util.List;
 public class Mainactivity extends activity {private ListView ListView;
 Private list<bean> Mdatas;

 Private Myadapter Madapter;
 @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);

 Setcontentview (R.layout.activity_main);
 Initview ();

 InitData ();
 }//Method: Initialize view private void Initview () {ListView = (ListView) Findviewbyid (R.id.listview);

 }//method; initialization data private void InitData () {Mdatas = new arraylist<bean> ();
 Load data into a collection bean bean = new Bean ("Android 1", "Android for ListView and GridView", "2015-05-04", "10086");

 Mdatas.add (Bean);
 Bean = new Bean ("Android 2", "Android for ListView and GridView Universal Adapters", "2015-05-04", "10086"); Mdatas.aDD (bean);
 Bean = new Bean ("Android 3", "Android for ListView and GridView Universal Adapters", "2015-05-04", "10086");

 Mdatas.add (Bean);
 Bean = new Bean ("Android 4", "Android for ListView and GridView Universal Adapters", "2015-05-04", "10086");

 Mdatas.add (Bean);

 Madapter = new Myadapter (this,mdatas) for data-bound adapters;
 Listview.setadapter (Madapter);
 }

}

The operation effect is as follows:

"Engineering Documents"
2015-05-04-baseadapter's traditional writing. rar

Second, the ListView of the Custom adapter encapsulation (Universal writing to write the adapter):
The full version of the code is as follows:

(1) Activity_main.xml:

<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=" Match_parent " >

<listview
 android:id= "@+id/listview"
 android:layout_width= "Match_parent"
 android: layout_height= "Match_parent" ></ListView>

</RelativeLayout>

(2) Item_listview.xml.xml: (Layout of individual item in listview)

<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=" Match_parent "Android: padding= "10DP" > <textview android:id= "@+id/titletv" android:layout_width= "Wrap_content" Android:layout_ height= "Wrap_content" android:singleline= "true" android:text= "new Android Skills" android:textcolor= "#444" Android: Textsize= "16sp"/> <textview android:id= "@+id/desctv" android:layout_width= "Match_parent" Android:layout_
 height= "Wrap_content" android:layout_below= "@+id/titletv" android:layout_margintop= "10DP" android:maxLines= "2" android:minlines= "1" android:text= "Android creates universal adapters for ListView and GridView" Android:textcolor= "#898989" android:textsize = "16sp"/> <textview android:id= "@+id/timetv" android:paddingtop= "3DP" android:layout_width= "Wrap_content" and roid:layout_height= "Wrap_content" android:layout_below= "@+id/desctv" android:layout_margintop= "10DP" android:text= "2015-05-04" android:textcolor= "#898989" android:textsize= "12sp"/> <textview android:pad ding= "2DP" android:id= "@+id/phonetv" android:gravity= "center" android:layout_width= "Wrap_content" Android:layout_ height= "Wrap_content" android:layout_below= "@+id/desctv" android:layout_margintop= "10DP" android:background= "# 2ed667 "android:drawableleft=" @mipmap/phone "android:drawablepadding=" 5DP "android:text=" 10086 "android:textColor="
 "#ffffff" android:textsize= "12SP" android:layout_alignparentright= "true"/> </RelativeLayout>

Its corresponding layout effect is as follows:

(3) Bean.java: DataSet

Package com.smyhvae.baseadapter.entities;

/**
 * Created by smyhvae on 2015/5/4.
 * * Public
class Bean {
 private String title;
 Private String desc;
 Private String time;
 Private String phone;

 Public beans () {
 } public

 Beans (string title, String desc, string 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;
 }
}

(4) "Reusable Code" Viewholder.java:

Package com.smyhvae.baseadapter.utils;
Import Android.content.Context;
Import Android.util.SparseArray;
Import Android.view.LayoutInflater;
Import Android.view.View;

Import Android.view.ViewGroup;
 /** * Created by smyhvae on 2015/5/4.
 * * Public class Viewholder {private sparsearray<view> mviews;
 private int mposition;

 Private View Mconvertview;
 Public Viewholder (Context context, viewgroup parent, int layoutid, int position) {this.mposition = position;

 This.mviews = new sparsearray<view> ();

 Mconvertview = Layoutinflater.from (context). Inflate (LayoutID, parent, false);

 Mconvertview.settag (this); public static Viewholder Get (context context, View Convertview, viewgroup parent, int layoutid, int position) {if (c
 Onvertview = = null) {Return to New Viewholder (context, parent, layoutid, position);
  else {Viewholder holder = (viewholder) convertview.gettag (); Holder.mposition = position;
 Even if Viewholder is reused, but position remember to update return holder; }
 }

 /*
 Get control by Viewid//using generic T, returns the subclass of View <t extends view> T getview (int viewid) {View view = Mviews.get (V

 IEWID);
  if (view = = null) {view = Mconvertview.findviewbyid (Viewid);
 Mviews.put (Viewid, view);
 Return (T) view;
 Public View Getconvertview () {return mconvertview;
 }

}

(5) Reusable Code Listviewadapter.java: a custom generic adapter that inherits from Baseadapter. In the future, if it is a custom ListView adapter, it's OK to inherit it  

Package com.smyhvae.baseadapter.utils;
Import Android.content.Context;
Import Android.view.LayoutInflater;
Import Android.view.View;
Import Android.view.ViewGroup;

Import Android.widget.BaseAdapter;

Import java.util.List;
 /** * Created by smyhvae on 2015/5/4. * Universal ListView Baseadapter, all ListView custom Adapter can inherit this class OH */public abstract class Listviewadapter<t> extends
 Baseadapter {//To allow subclasses to access, the property is set to protected protected context mcontext;
 protected list<t> Mdatas;
 protected Layoutinflater Minflater; private int layoutid; Different ListView item layouts can be different, so separate the layouts out of the public listviewadapter (context, list<t> datas, int layoutid) {This
 . Mcontext = Context;
 Minflater = Layoutinflater.from (context);
 This.mdatas = datas;
 This.layoutid = LayoutID;
 @Override public int GetCount () {return mdatas.size ();
 @Override public T getitem (int position) {return mdatas.get (position);
 @Override public long getitemid (int position) {return position; }

 @Override public View getview (int position, View Convertview, ViewGroup parent) {//Initialize Viewholder, using generic viewholder, one-line generation The code is done. Initialization of viewholder Viewholder holder = viewholder.get (Mcontext, Convertview, parent, layoutid, position);
 LayoutID is the layout of the individual item convert (holder, getitem (position)); return Holder.getconvertview ();

This line of code should be noted}//Publish the Convert method out of public abstract void convert (Viewholder holder, T);
 }

(6) Listviewadapterwithviewholder.java: Inherit from Listviewadapter

Package com.smyhvae.baseadapter;
Import Android.content.Context;

Import Android.widget.TextView;
Import Com.smyhvae.baseadapter.entities.Bean;
Import Com.smyhvae.baseadapter.utils.ListViewAdapter;

Import Com.smyhvae.baseadapter.utils.ViewHolder;

Import java.util.List;
 /** * Created by smyhvae on 2015/5/4. * * public class Listviewadapterwithviewholder extends listviewadapter<bean> {//myadapter need a context, Get Layout.inflater through the context, and then load the item layout public by Inflater Listviewadapterwithviewholder (context, list<
 Bean> datas) {Super (context, datas, R.layout.item_listview); @Override public void convert (Viewholder holder, Bean Bean) {(TextView) Holder.getview (R.id.titletv). SetText (Bea
 N.gettitle ());
 ((TextView) Holder.getview (R.ID.DESCTV)). SetText (Bean.getdesc ());
 ((TextView) Holder.getview (R.id.timetv)). SetText (Bean.gettime ());

((TextView) Holder.getview (R.id.phonetv)). SetText (Bean.getphone ());
 /* TextView TV = Holder.getview (R.id.titletv); Tv.setteXT (...);
 ImageView view = GetView (Viewid);
Imageloader.getinstance (). Loadimag (View.url);
 */
 }
}

(7) Mainactivity.java:

Package com.smyhvae.baseadapter;
Import android.app.Activity;
Import Android.os.Bundle;

Import Android.widget.ListView;

Import Com.smyhvae.baseadapter.entities.Bean;
Import java.util.ArrayList;

Import java.util.List;
 public class Mainactivity extends activity {private ListView ListView;

 Private list<bean> Mdatas;

 Private Listviewadapterwithviewholder Listviewadapterwithviewholder;
 @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);

 Setcontentview (R.layout.activity_main);
 Initview ();
 InitData ();
 }//Method: Initialize view private void Initview () {ListView = (ListView) Findviewbyid (R.id.listview);

 }//method; initialization data private void InitData () {Mdatas = new arraylist<bean> ();
 Load data into a collection bean bean = new Bean ("Android 1", "Android for ListView and GridView", "2015-05-04", "10086");

 Mdatas.add (Bean);
 Bean = new Bean ("Android 2", "Android for ListView and GridView Universal Adapters", "2015-05-04", "10086");

 Mdatas.add (Bean); Bean = new Bean ("Android 3", "Android for ListView and GridView to create Universal adapters", "2015-05-04", "10086");

 Mdatas.add (Bean);
 Bean = new Bean ("Android 4", "Android for ListView and GridView Universal Adapters", "2015-05-04", "10086");

 Mdatas.add (Bean);

 Listviewadapterwithviewholder = new Listviewadapterwithviewholder (this, mdatas) for data-bound adapters;

 Listview.setadapter (Listviewadapterwithviewholder);
 }
}

Operation Effect:

In this case, every time you write a ListView, do it: direct import Viewholder.java and Listviewadapter, and then write a custom adapter inherited from Listviewadapter on the line.

Package of "Engineering document" 2015-05-04-baseadapter. rar

third, frequently asked questions:

1, the Item control preemption Focus:

Suppose there is a checkbox in the item, and after running the program, it is found that only the checkbox can be clicked, and the other locations in the item cannot be clicked (including clicking the entire item or not responding), because the checkbox grabs the entire item's focus. The following options are:

Option 1: Set the property for the checkbox: android:focusable = "false"
Option 2: Set the property for this item: android:descendantfocusability = "Blocksdescendants"

Don't let the item focus on the top down.

2, ListView reuse leads to content disorder.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.