How to use the ListView

Source: Internet
Author: User

The ListView is one of the most important components in Android software development, basically a software that uses a ListView, and today I use a demo to show you how to draw a nice list using the ListView component. Says the ListView has to say the adapter adapter, because only through adapter can you map the data in the list to the ListView.

In the development of Android, the most adapter can be divided into
Arrayadapter<t>,
Baseadapter,
CursorAdapter,
Headerviewlistadapter,
Resourcecursoradapter,
Simpleadapter,
Simplecursoradapter,
Wrapperlistadapter
The most commonly used in software development is Arrayadapter<t> , baseadapter, simpleadapter, today I use a piece of code to explain to you how to use the ListView control.


1. Simple ListView
If there are no overly complex items in the list, we can simply go to New arrayadapter () to draw the list without inheriting the arrayadapter and overriding its method. But if the list is too complex, you need to use a custom layout to implement the list. Item.xml:
<span style= "font-family: Song body, Arial Narrow, Arial, serif;" ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"    android:layout_width= "match _parent "    android:layout_height=" match_parent "    android:orientation=" vertical ">    <listview        Android:id= "@+id/list1"        android:layout_width= "fill_parent"        android:layout_height= "Fill_parent" >    </listview></linearlayout></span><span style= "font-family: Song Body, ' Arial Narrow ', Arial, Serif line-height:26.6666679382324px; Background-color:rgb (255, 255, 255); " > </span>

<span style= "FONT-SIZE:24PX;" ></span><span style= "FONT-SIZE:14PX;" >private ListView listview;private string[] Listviewarray = {"Skyfin", "Locojyw", "Facker", "Gad"};@ overrideprotected void OnCreate (Bundle savedinstancestate) {//TODO auto-generated method Stubsuper.oncreate ( Savedinstancestate); Setcontentview (r.layout.list1); listview = (ListView) Findviewbyid (R.ID.LIST1); Listview.setadapter (New arrayadapter<string> (this, Android. R.layout.simple_list_item_1,listviewarray)); Listview.setonitemclicklistener (new Onitemclicklistener () {@ overridepublic void Onitemclick (adapterview<?> parent, View view,int position, long ID) {//TODO auto-generated Meth Od stubtoast.maketext (Listadapteractivity.this, "You have selected" + listviewarray[position], Toast.length_long). Show ();}  );} </span>


2. List of ListView with Headers

Use Simpleadapter Note that you need to use map<string,object> item to save the title and text of each item in the list, and new Simpleadapter to write the data in the map. The program will help us draw the list.

Private ListView listview;private string[] Listviewtitlearray = {"Skyfin", "Locojyw", "Facker", "Gad"};p rivate string[] Listviewsubtitlearray = {"", "", "", "")};p rivate arraylist<map<string, object>> mdata= New Arraylist<map<string,object>> (); @Overrideprotected void OnCreate (Bundle savedinstancestate) {//TODO Auto-generated method Stubsuper.oncreate (savedinstancestate); Setcontentview (r.layout.list1); listview = (ListView)    Findviewbyid (R.ID.LIST1);      int lengh = Listviewtitlearray.length;          for (int i =0; i < Lengh; i++) {map<string,object> item = new hashmap<string,object> ();          Item.put ("title", Listviewtitlearray[i]);          Item.put ("text", Listviewsubtitlearray[i]);       Mdata.add (item); } simpleadapter adapter = new Simpleadapter (Getapplicationcontext (), Mdata, Android. R.layout.simple_list_item_2, new string[]{"title", "Text"},new int[]{android. R.id.text1,android. R.ID.TEXT2}); Listview.setadapter (Adapter); Listview.setonitemclicklistener (new Onitemclicklistener () {@Overridepublic void Onitemclick (adapterview<?> Parent, View view,int position, long ID) {//TODO auto-generated method Stubtoast.maketext (Simpleadapteractivity.this, "  You have selected "+ listviewtitlearray[position", Toast.length_long). Show (); }});}

3. List of ListView with pictures

The use of Simpleadapter to operate but the construction of simpleadapter need to use our own written layout to complete, because the system layout is not enough to meet the requirements, the same map<string,object> item To save the contents of each item in the list, such as the title of the picture .

add our own list layout picture title content

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" fill_parent "    android:layout_height=" 45DP "    android:orientation=" Horizontal ">    <imageview        android:id=" @+id/image "        android:layout_width=" 45dip "        android: layout_height= "45dip"        android:src= "@drawable/drawer_menu_icon_setting_nor"/>    <textview        Android:id= "@+id/textview"        android:layout_width= "wrap_content"        android:layout_height= "Wrap_content"        android:layout_gravity= "center"        android:paddingleft= "13dip"        android:textsize= "30dip"        Android:text= "AAA"/></linearlayout>


Private ListView listview;private string[] Listviewarray = {"Technical questions", "open Source software", "blog area", "Git Client"};p rivate int[] Listviewimagearray = {R.drawable.drawer_menu_icon_quest_nor,r.drawable.drawer_menu_icon_opensoft_nor,    R.drawable.drawer_menu_icon_blog_nor,r.drawable.drawer_menu_icon_gitapp_nor}; arraylist<map<string,object>> mdata= new arraylist<map<string,object>> (); overrideprotected void OnCreate (Bundle savedinstancestate) {//TODO auto-generated method Stubsuper.oncreate (    Savedinstancestate); Setcontentview (R.LAYOUT.LIST3); listview = (ListView) Findviewbyid (R.ID.LIST3);      int lengh = Listviewarray.length;          for (int i =0; i < Lengh; i++) {map<string,object> item = new hashmap<string,object> ();          Item.put ("image", listviewimagearray[i]);          Item.put ("title", Listviewarray[i]);       Mdata.add (item);  } simpleadapter adapter = new Simpleadapter (this,mdata,r.layout.item3, new string[]{"image", "title"},new Int[]{r.id.image,r.id.textview}];      Listview.setadapter (adapter); Listview.setonitemclicklistener (New Onitemclicklistener () {@Override public void Onitemclick (Adaptervie W<?> Adapterview, view view, int position, long id) {Toast.maketext (piclistadapteractivity.th          Is,listviewarray[position], Toast.length_long). Show ();  }      }); }



4. Customizing layouts Baseadapter modifying list colors
because the method of drawing the list by directly constructing the layout of the system is certainly limited, we need to rewrite the drawing method, write a class to inherit the Baseadapter and implement the method in this class, and the ListView will first call Getcout () at the beginning of the drawing. The method gets the number of draws and then instantiates its own defined baseadapter through the GetView () method to draw the ListView one layer at a level, so we can modify the content of the drawing arbitrarily, based on the position (currently drawn ID). Make a nice looking listview, here's an example I'll change the color of each list by rewriting GetView and make the user select the highlighted state.
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/    Android "Android:layout_width=" Fill_parent "android:layout_height=" 60dip "android:orientation=" Horizontal "> <imageview android:id= "@+id/iamgeview" android:layout_width= "45dip" android:layout_height= "45dip "android:layout_gravity=" center "android:src=" @drawable/drawer_menu_icon_night_nor "/> <textview A Ndroid:id= "@+id/title" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Andro id:layout_gravity= "center" android:paddingleft= "20dip" android:text= "Hello" android:textsize= "25dip"/ > <textview android:id= "@+id/text" android:layout_width= "wrap_content" android:layout_height= "Wrap_ Content "android:layout_gravity=" center "android:paddingleft=" 20dip "android:text=" Hello "Android Oid:textsize= "25dip"/></lineaRlayout> 


Simple Adapter
Package Com.skyfin.listview;import Java.util.arraylist;import Java.util.list;import android.content.context;import Android.util.log;import Android.view.layoutinflater;import Android.view.view;import Android.view.ViewGroup;import Android.widget.baseadapter;import Android.widget.imageview;import Android.widget.textview;public class MyAdapter      Extends Baseadapter {Layoutinflater minflater = null;      list<iteminfo> list = new arraylist<iteminfo> ();         Public Myadapter (context context, list<iteminfo> List) {super ();          This.minflater = Layoutinflater.from (context);                This.list = list;      } @Override public int getcount () {return list.size ();      } @Override public Object getItem (int position) {return null;      } @Override public long getitemid (int position) {return 0; } @Override public view getView (int position, view Convertview, ViewGroupParent) {log.i ("Hello", "123");    TextView Titletextview = null;    TextView TextView = null;            ImageView img = null;                  if (Convertview = = null) {Convertview = minflater.inflate (R.LAYOUT.ITEM4, NULL);                  Titletextview = (TextView) Convertview.findviewbyid (r.id.title);                  TextView = (TextView) Convertview.findviewbyid (R.id.text);            img = (ImageView) Convertview.findviewbyid (R.id.iamgeview);             } titletextview.settext (List.get (position). GetTitle ());              Textview.settext (List.get (position). GetText ());          Img.setimageresource (List.get (position). GetImage ());      return convertview;   }}

public class Baseadapteractivity extends Activity {private ListView listview;private myadapter mydapter;private string[] Listviewarray = {"Skyfin", "Locojyw", "Facker", "Gad"};p rivate string[] listviewarraynum = {"2013", "2014", "2015", "20 "};p rivate int[] Listviewimagearray = {R.drawable.drawer_menu_icon_quest_nor,r.drawable.drawer_menu_icon_ Opensoft_nor,r.drawable.drawer_menu_icon_blog_nor,r.drawable.drawer_menu_icon_gitapp_nor}; List<iteminfo> Listiteminfos = null; @Overrideprotected void OnCreate (Bundle savedinstancestate) {//TODO Auto-generated method Stubsuper.oncreate (savedinstancestate); Setcontentview (R.LAYOUT.LIST4); listview = (ListView) Findviewbyid (R.ID.LIST4); Listiteminfos = new arraylist<iteminfo> (); for (int i =0;i<listviewarray.length;i++ ) {ItemInfo iteminfo = new ItemInfo (Listviewarray[i], listviewarraynum[i], listviewimagearray[i]); ListIteminfos.add ( ItemInfo);} Mydapter = new Myadapter (this, Listiteminfos); Listview.setadapter (mydapter); listview.setonitEmclicklistener (New Onitemclicklistener () {@Overridepublic void Onitemclick (adapterview<?> adapterview, View View,int position, long id) {Toast.maketext (Getapplicationcontext (), listviewarray[position],toast.length_long). Sh       ow (); }});}}


5. Custom Layout Arrayadapter
Arrayadapter is a subclass of Baseadapter, Arrayadapter not only has all the methods of Baseadapter, but also customizes some new methods to process the list items. So simply from the functional energy to the arrayadapter far stronger and baseadapter, if it is to draw some number of less than the list recommended to use Baseadapter if you draw some more complex list items and list items A lot of suggestions to use Arrayadapter.

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"    android:layout_width= "Fill_ Parent "    android:layout_height=" 60dip "    android:orientation=" Horizontal ">    <imageview        Android:id= "@+id/photo"        android:layout_width= "45dip"        android:layout_height= "45dip"        android:layout_ gravity= "center"        android:src= "@drawable/drawer_menu_icon_night_nor"/>    <button android:id= "@+id/ BTN "        android:layout_width=" wrap_content "        android:layout_height=" wrap_content "        android:layout_ gravity= "center"        android:paddingleft= "20dip"        android:text= "Hello"        android:textsize= "25dip"/> </LinearLayout>

Package Com.skyfin.listview;import Android.content.context;import Android.view.layoutinflater;import Android.view.view;import Android.view.view.onclicklistener;import Android.view.viewgroup;import Android.widget.arrayadapter;import Android.widget.button;import Android.widget.imageview;import Android.widget.toast;public class Myarrayadapter extends arrayadapter<object> {private int[] Listviewimagearray = {R.drawable.drawer_menu_icon_quest_nor,r.drawable.drawer_menu_icon_opensoft_nor,r.drawable.drawer_menu_icon_      Blog_nor,r.drawable.drawer_menu_icon_gitapp_nor};int Mtextviewresourceid = 0;      Private Context Mcontext;          Public Myarrayadapter (context context, int Textviewresourceid) {Super (context, Textviewresourceid);          Mtextviewresourceid = Textviewresourceid;      Mcontext = context;       } private int[] colors = new int[] {0xff626569, 0xff4f5257};    public int GetCount () {return 4; } @Override Public Boolean AreallitemSenabled () {return false;      } public Object GetItem (int position) {return position;      } public long Getitemid (int position) {return position;            Public View GetView (final int position, View Convertview, ViewGroup parent) {ImageView iamge = null;          button button = null;  if (Convertview = = null) {Convertview = Layoutinflater.from (Mcontext). Inflate (Mtextviewresourceid,          NULL);          Iamge = (ImageView) Convertview.findviewbyid (R.id.photo);          Button = (button) Convertview.findviewbyid (R.ID.BTN); Button.setonclicklistener (New Onclicklistener () {@Override public void OnClick (Vi                            EW arg0) {toast.maketext (GetContext (), "The first you click" +position + "buttons", Toast.length_long). Show ();          }          });          } iamge.setimageresource (Listviewimagearray[position]);      return convertview;    }  } 


public class Arrayadapteractivity extends Activity {private ListView listview;private myarrayadapter mydapter;@ overrideprotected void OnCreate (Bundle savedinstancestate) {//TODO auto-generated method Stubsuper.oncreate ( Savedinstancestate); Setcontentview (R.LAYOUT.LIST5); listview = (ListView) Findviewbyid (R.ID.LIST5); mydapter = new Myarrayadapter (this, R.LAYOUT.ITEM5); Listview.setadapter (Mydapter); Listview.setonitemclicklistener (new Onitemclicklistener () {@Overridepublic void Onitemclick (adapterview<?> adapterview, View view,int position, long ID) {        toast.maketext (Getapplicationcontext (), Position,toast.length_long). Show ();}}       );}}



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

How to use the ListView

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.