The Android ListView control is detailed

Source: Internet
Author: User


1.ArrayAdapterThis is the simplest of all, just accept the TextView control by default, and it's just one.
        ListView = New ListView (this);   Note that you do not use the//style of the XML file is the style provided by Android          Listview.setadapter (New arrayadapter<string> (this, Android). R.layout.simple_expandable_list_item_1,getdata ()));        

This means that the XML file is not used, and a listview,android is directly new. R.layout.simple_expandable_list_item_1 is the style provided by Android. GetData () returns a List<string> collection although there seems to be no technical content, but if you want to use an adapter like this, the two three lines of code is done, do not need to configure the XML file, only need to give a set of the line.


2.SimpleCursorAdapter (for database service, actually contentprovider)Leng adapter, before the code to explain the course, so on the Internet to find some information, roughly like this.

Its design is based on the database service generationrequires permission <uses-permission android:name= "Android.permission.READ_CONTACTS"/>the Cursor is a collection of each row. Use Movetofirst () to locate the first row. You must know the name of each column. You must know the data type of each column. The Cursor is a random data source. All data is obtained by subscript.

Important methods for Cursor:

<span style= "FONT-SIZE:14PX;" > Close ()--Closes the cursor, frees the resource copystringtobuffer (int columnindex, Chararraybuffer buffer)--retrieves the text of the requested column in the buffer and stores it getColumnCount ()--Returns the total number of all columns Getcolumnindex (string columnName)-Returns the name of the specified column if there is no return -1 Getcolumnindexorthrow (string ColumnName)--Returns the specified column name from zero, and throws a IllegalArgumentException exception if it does not exist. getcolumnname (int columnindex)-Returns the column name from the given index · Getcolumnnames ()--Returns the column name of a string array GetCount ()--Returns the number of rows in the cursor movetofirst ()--Moves the cursor to the first row movetolast ()--Moves the cursor to the last row · MoveToNext ()--Move the cursor to the next line movetoposition (int position)--Move the cursor to an absolute position movetoprevious ()--Move the cursor to the previous line </span>
<span style= "FONT-SIZE:14PX;" > Access the Cursor's subscript to get the data in int namecolumnindex = Cur.getcolumnindex (people.name); String name = cur.getstring (namecolumnindex);</span>

Now let's see how we loop the Cursor out of the data we need.

<span style= "FONT-SIZE:14PX;" >while (Cur.movetonext ()) {    //cursor moved successfully   String email = cursor.getstring (Cursor.getcolumnindex (Ruixin.email) );   Startmanagingcursor (cursor);  Close cursor after lookup    //Remove Data}</span>


/* Getapplicationcontext (): The life cycle is the entire application, the application is destroyed, it is destroyed.  * This: Represents the current activity in the activity, in other words, activity.this can be abbreviated as this in the activity.  * Getapplication (): Share global data in andorid development;                 */listview = new ListView (this); Get phone Address Book information This and containprovider about cursor cursor = getcontentresolver (). query (People.content_uri, NULL, NU        ll, NULL, NULL);           Startmanagingcursor (cursor); /* The life cycle of the cursor object can be automatically synchronized with the current activity, eliminating its own management of the cursor * 1. This method uses the assumption that there are many data records in the cursor result set.   Therefore, before using, the cursor is NULL to determine if the cursor = NULL, and then use this method 2. If you use this method, you will end up using Stopmanagingcursor () to stop the error. 3. The purpose of this method is to give the retrieved cursor object to activity management so that the cursor's life cycle can be automatically synchronized with the activity, saving itself from manual management. */ListAdapter ListAdapter = new Simplecursoradapter (this, Android. R.layout.simple_expandable_list_item_1, cursor, new string[]{people.name}, new int[]{android.        R.ID.TEXT1});        Listview.setadapter (ListAdapter); Setcontentview (ListView);



3.SimpleAdapter
/*  This is a simple adapter that can map static data to a defined view in an XML file. You can specify a list (such as a ArrayList) type of data that is made up of map. Each entry in ArrayList corresponds to a row in the list. Maps contains data for each row. You can specify an XML layout to specify the view for each row, based on the data map keyword in the map to the specified view. Binding data to the view is divided into two stages, first, if Simpleadapter.viewbinder is set, then this setting of the Viewbinder Setviewvalue (Android.view.View, Object, String) will be called. If the return value of Setviewvalue is true, the binding is completed and the system default binding implementation is no longer called. If the return value is false, the view binds the data in the following order:  If the view implements a checkable (for example, a checkbox), the expected bound value is a Boolean type. TextView. The expected binding value is a string type that is bound by calling Setviewtext (TextView, String).  ImageView, the expected binding value is either a resource ID or a string that binds the data by calling Setviewimage (ImageView, int) or Setviewimage (ImageView, String).  If no suitable binding occurs, IllegalStateException will be thrown.  */ListView Listview=new ListView (This);     Simpleadapter adapter = new Simpleadapter (This,getdata (), R.layout.vlist,                new string[]{"title", "Info", "img"},                new int[]{r.id.title,r.id.info,r.id.img});     Listview.setadapter (adapter);     Setcontentview (ListView);


Get Data list
Private list<map<string, object>> getData () {/* for simpleadapter This, this seems to be a static list<map<string, Object>> a list consisting of a map. Each entry in the list corresponds to a row in the list, and each map should contain all of the keys specified in the from parameter, the run environment of the view that is associated with the context Simpleadapter data, a list of the map. Each entry in the list corresponds to a row in the list, and each map should contain a resource ID for the layout file that defines the list item resource a key specified in the from parameter. The layout file should contain at least those idfrom that are defined in to and the ID of the view that will be added to the map map to bind the data, which corresponds to the from parameter, which should be all TextView */list<map<string        , object>> list = new arraylist<map<string, object>> ();        map<string, object> map = new hashmap<string, object> ();        Map.put ("title", "Technology");        Map.put ("info", "When Ai reaches Singularity");  Map.put ("img", R.DRAWABLE.I1);         Resource file ID list.add (map);        Map = new hashmap<string, object> ();        Map.put ("title", "Society");        Map.put ("Info", "in the end to help the elderly");              Map.put ("img", R.DRAWABLE.I2);         List.add (map);        Map = new hashmap<string, object> ();   Map.put ("title", "NBA");     Map.put ("Info", "West final I want to be a rocket win");        Map.put ("img", R.DRAWABLE.I3);                 List.add (map);    return list; }




3.SimpleAdapter (Play it yourself) if you add a button and a picture to a ListView and add an event to the button. So how to, in list
<span style= "White-space:pre" ></span>     listview = new ListView (this);     Mdata = GetData ();  Get Data     Myadapter adapter = new Myadapter (this);     Listview.setadapter (adapter);     Setcontentview (ListView);


Custom adapters need to inherit Baseadapter
public class Myadapter extends baseadapter{/** * acts like Findviewbyid () * Layoutinflater is used to find the XML under res/layout/     The layout file is instantiated, and Findviewbyid () is the specific widget control (such as button, TextView, and so on) that is found under the XML layout file. * 1, for a non-loaded or want to dynamically load the interface, you need to use Layoutinflater.inflate () to load, 2, for an already loaded interface, you can use Activiyt.findviewbyid ()     method to obtain the interface elements.                          */Private Layoutinflater minflater;  Public Myadapter (Context context) {This.minflater = Layoutinflater.from (context);        instantiation} @Override public int getcount () {return mdata.size ();        } @Override public Object getItem (int arg0) {return null;        } @Override public long getitemid (int arg0) {return 0;          /** * Adapter is a bridge between the ListView interface and the data, and when each item in the list is displayed to the page, the adapter GetView method is called to return a view. * Each creation of the view is time-consuming, so the GetView method incoming Convertview should take full advantage of the = NULL judgment * * Optimize the load speed of the ListView to let Convertview match the column Table type, and the maximumDegree of re-use Convertview * Define a Viewholder, set the Convetview tag to Viewholder, and do not re-use it when empty * */@Ove Rride public View getView (int position, view Convertview, ViewGroup parent) {Viewholder ho            Lder = null;              if (Convertview = = null) {holder=new viewholder ();  /* overload form, return value is view object * public view inflate (int resource, ViewGroup root) public view inflate (Xmlpullparser Parser, ViewGroup root) public view inflate (Xmlpullparser parser, ViewGroup root, Boolean attachtoroot) public view INFL Ate (int resource, ViewGroup root, Boolean attachtoroot) */Convertview = Minflater.inflate (r.layout.vlist2                , null);                Holder.img = (ImageView) Convertview.findviewbyid (r.id.img);                Holder.title = (TextView) Convertview.findviewbyid (r.id.title);                Holder.info = (TextView) Convertview.findviewbyid (r.id.info); HOLDER.VIEWBTN = (Button) CONVERTVIew.findviewbyid (R.ID.VIEW_BTN);                             Convertview.settag (holder);  }else {holder = (Viewholder) convertview.gettag (); Re-use the match used by the/** is a holder of the class, he generally has no method, only the property, the function is a temporary storage, the way you getview each return of the view saved, * Can be reused next time.                 The advantage of this is that you do not have to go to the layout file every time to get your view, improve the efficiency. */} Holder.img.setBackgroundResource ((Integer) mdata.get (position). Get ("Im            G "));            Holder.title.setText (String) mdata.get (position). Get ("title"));                         Holder.info.setText (String) mdata.get (position). Get ("info"));                                  /** * can also add event response here, it's absolutely great. */Holder.viewBtn.setOnClickListener (new View.onclicklistener () {                                 @Override public void OnClick (View v) {showinfo ();            }            });        return convertview; }                    }


Viewholder is equivalent to a javabean, only attributes have no method



/**     * When dealing with time-consuming resource loads, the following points need to be made to make your load faster and smoother: 1.   The adapter is modified in the main thread of the interface 2.   Data can be obtained anywhere but data 3 should be requested in another place.   Commit the adapter change in the thread of the main interface and call the Notifydatasetchanged () method     * @author Suibian * */public        final class viewholder{ Public        ImageView img;        public TextView title;        public TextView info;        Public Button viewbtn;    }


Reference Blog: http://www.cnblogs.com/allin/archive/2010/05/11/1732200.html#


I'm a rookie, I'm on my way.
May 20, 2015 10:30:28

The Android ListView control is detailed

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.