Use custom adapter for listview

Source: Internet
Author: User

1. Principle Analysis

The adapter is very important for listview. It is in the middle of the listview and the data source, and is responsible for creating a specific view for the listview. Previously we mentioned that listview uses the view reuse technology. Even if you need to display a large number of data lists, it can work efficiently. It always tries to reuse existing views.

The following describes the view Reuse Technology:

In short, assume that a listview contains seven items, from top to bottom, which are Item1 ~ Item7: when a user slides up the screen, Item1 will scroll out of the screen area. Item1 is not destroyed, but placed in the recycle bin (recycler ). When listview needs to display the next item, it will first check whether there are available items in the recycle bin, just found Item1, and reuse Item1 directly. Listview transmits the obtained Item1 and the new position (position8) to the getview method of the adapter. In the getview method, the corresponding data is retrieved from the data source based on position8 and overwritten to item1, in this case, Item1 becomes item8. Finally, the new item8 is displayed on the page in listview.

When the listview contains items of different views, there is an int getviewtypecount () method in the adapter to return the number of view types used by the item (1 by default ). Listview creates a storage area in the recycle bin Based on the return value of this method of the adapter. The Int getitemviewtype (INT position) of the adapter: obtains the view type used by the corresponding item based on the position. The listview will create different storage regions in the recycle bin based on the type. The listview will retrieve the correct type of view based on position for reuse before calling the getview method of the adapter.

In the preceding two methods, listview achieves reuse of views in the case of a single item view and multiple item views.

In the previous explanation of "listview binding emptyview", we performed a simple custom implementation of adapter. Today we will explain how to display items with different views in listview. If only the item of a single view is displayed, you only need to override the following four methods of baseadapter:

Int getcount (): returns the total number of data items in the data source.

Object getitem (INT position): obtains data items from the data source based on position.

Long getitemid (INT position): obtains the data item ID from the data source based on position.

View getview (INT position, view convertview, viewgroup parent): Creates a view based on position. It is the most important method in the adapter. listview creates a view through it.

This is also a method that must be rewritten when a custom adapter is used.

To implement a multi-view item listview, you also need to override the following methods of the adapter (not required ):

Int getviewtypecount (): return the number of view types used by the item. The default value is 1.

Int getitemviewtype (INT position): obtains the view type used by the corresponding item based on position.

Boolean isenabled (INT position): sets whether the corresponding item is available based on position, that is, whether the UI event can be received.

Getitemviewtype and getviewtypecount usually need to be paired

2. Example Analysis

The effect of this demo is that the letters are displayed separately in listview based on the different initials of the word. The first letter of a word is separated by each part and is displayed in a view different from that of a letter.
Therefore, two views of different styles are required in the demo. They are:

First_letter_item.xml, the Code is as follows:

<?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="fill_parent"    android:orientation="vertical" >            <TextView android:id="@+id/firstletter"        style="?android:attr/listSeparatorTextViewStyle"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:textColor="@android:color/white"        />  </LinearLayout>

 

The code for word_item.xml is as follows:

<?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="fill_parent"    android:orientation="vertical"        android:paddingBottom="8dp" >            <TextView        android:id="@+id/word"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:paddingLeft="8dp"        android:paddingRight="8dp"        android:paddingTop="8dp"        android:singleLine="true"        android:textColor="?android:attr/textColorPrimary"        android:textSize="10pt"        android:textStyle="bold" /></LinearLayout>

The layout files of these two items are very simple. They all use the linearlayout layout. There is only one textview display text in the layout, which is not described too much.

The Java code is as follows:

Package COM. devdiv. test. listviewtest6; import android. app. listactivity; import android. OS. bundle; import android. view. layoutinflater; import android. view. view; import android. view. viewgroup; import android. widget. baseadapter; import android. widget. listview; import android. widget. textview; public class listviewtest6activity extends listactivity {private layoutinflater minflater = NULL; Private Static final String [] DATA = {"A", "abnormal", "acute", "ambitious", "B", "Bed", "bad", "C ", "Compare", "communication", "D", "Dad", "E", "element"}; private letteradapter mletteradapter;/** called when the activity is first created. * // @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); minflater = layoutinflater. from (this); mletteradapter = new letteradapter (data); setlistadap Ter (mletteradapter);} private class letteradapter extends baseadapter {private string [] letter ={}; // defines two int constants to mark different item views public static final int first_letter_item = 0; public static final int word_item = 1; Public letteradapter (string [] data) {letter = data ;}@ override public int getitemviewtype (INT position) {// todo auto-generated method stub if (letter [position]. length () = 1) {return F Irst_letter_item;} else {return word_item; }}@ override public int getviewtypecount () {// todo auto-generated method stub // because there are two views, SO 2 return 2;} @ override public Boolean isenabled (INT position) {// todo auto-generated method stub return (letter [position]. length ()! = 1) ;}@ override public int getcount () {// todo auto-generated method stub return letter. length ;}@ override public object getitem (INT position) {// todo auto-generated method stub return letter [position] ;}@ override public long getitemid (INT position) {// todo auto-generated method stub return position;} @ override public view getview (INT position, view convertview, viewgroup parent) {// todo auto-generated method stub viewholder VL = NULL; If (convertview = NULL) {VH = new viewholder (); If (getitemviewtype (position) = first_letter_item) {convertview = getlayoutinflater (). inflate (R. layout. first_letter_item, parent, false); // convertview = minflater. inflate (R. layout. first_letter_item, null); Vl. TV = (textview) convertview. findviewbyid (R. id. firstletter);} else {convertview = getlayoutinflater (). inflate (R. layout. word_item, parent, false); // convertview = minflater. inflate (R. layout. word_item, null); Vl. TV = (textview) convertview. findviewbyid (R. id. word);} convertview. settag (VL);} else {HH = (viewholder) convertview. gettag ();} FLAC. TV. settext (letter [position]); Return convertview;} class viewholder {textview TV ;}}}

The custom adapter used in this demo is more complex than the previous one. You can use the rewrite method to display the effects of the two views.
The Code is as follows:

@ Overridepublic int getitemviewtype (INT position) {// todo auto-generated method stub if (letter [position]. length () = 1) {return first_letter_item;} else {return word_item; }}@ overridepublic int getviewtypecount () {// todo auto-generated method stub // because there are two views, 2 return 2;} is returned ;}

The public int getviewtypecount () method returns 2, indicating that there are two views. In the public int getitemviewtype (INT position) method, first_letter_item (0, represents the "first letter View") and word_item (1, represents the "word view ").

Set the "First Letter" item to not receive UI events, which is also based on the length of the string, the Code is as follows:

@Overridepublic boolean isEnabled(int position) {                // TODO Auto-generated method stub                                        return (letter[position].length() != 1);                }

In the above Java code, the most important thing is the implementation of the public view getview (INT position, view convertview, viewgroup parent) method. The Code is as follows:

@Overridepublic View getView(int position, View convertView, ViewGroup parent) {                // TODO Auto-generated method stub                                ViewHolder vh = null;                                if(convertView == null) {                                                                vh = new ViewHolder();                                                                if(getItemViewType(position) == FIRST_LETTER_ITEM) {                                                convertView = getLayoutInflater().inflate(R.layout.first_letter_item, parent, false);                                                //convertView = mInflater.inflate(R.layout.first_letter_item, null);                                                vh.tv = (TextView) convertView.findViewById(R.id.firstletter);                                                                                } else {                                                convertView = getLayoutInflater().inflate(R.layout.word_item, parent, false);                                        //convertView = mInflater.inflate(R.layout.word_item, null);                                                vh.tv = (TextView) convertView.findViewById(R.id.word);                                }                                convertView.setTag(vh);                } else {                                vh = (ViewHolder) convertView.getTag();                }                vh.tv.setText(letter[position]);                return convertView;}class ViewHolder{                TextView tv;}

In this method, view reuse technology is used. If converview is empty, the corresponding XML layout file is parsed based on different positions, and the obtained textview is obtained through findviewbyid, and use convertview. settag (VH) stores the control in viewholder. If convertview is not empty, the previously stored viewholder is obtained by using the method of h_= (viewholder) convertview. gettag.

Note that:
The settag (Object Tag) in the view indicates that an extra data (or a flag can be used to distinguish a group of controls of the same type) is added to the view, and gettag () can be used later () extract the data.

In addition, the viewholder is placed in converview to facilitate the extraction of the VH when the view is reused. You can directly set the textview to save the findviewbyid process. This is a tip when using 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.