Android ListView Detailed

Source: Internet
Author: User

Transferred from: http://www.cnblogs.com/allin/archive/2010/05/11/1732200.html

In Android development, the ListView is a more commonly used component that presents the content as a list and can be displayed adaptively based on the length of the data. The use of the ListView was collated and a small example was written, such as.

The display of a list requires three elements:

1. Listveiw The view used to display the list.

2. The adapter is used to map data to mediations on the ListView.

3. The data is specific to the string, picture, or base component that will be mapped.

Based on the list of adapter types, the list is divided into three types, arrayadapter,simpleadapter and Simplecursoradapter

One of the easiest arrayadapter to display is a single line of words. Simpleadapter has the best extensibility and can customize various effects. Simplecursoradapter can be considered as a simple combination of the Simpleadapter database, can be in the aspect of the contents of the database as a list of the form of display.

Let's start with the simplest listview:

123456789101112131415161718192021222324252627282930 /** * @author allin * */publicclassMyListView extendsActivity {    privateListView listView;    //private List<String> data = new ArrayList<String>();    @Override    publicvoidonCreate(Bundle savedInstanceState){        super.onCreate(savedInstanceState);                listView = newListView(this);        listView.setAdapter(newArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1,getData()));        setContentView(listView);    }                privateList<String> getData(){                List<String> data = newArrayList<String>();        data.add("测试数据1");        data.add("测试数据2");        data.add("测试数据3");        data.add("测试数据4");                returndata;    }}

The above code uses Arrayadapter (context context, int Textviewresourceid, list<t> objects) to assemble the data, To assemble this data requires an adapter that connects the ListView object and array data to fit the two, and the Arrayadapter construct requires three parameters, the this, and the layout file (note here that the layout file describes the layout of each row of the list, Android. R.layout.simple_list_item_1 is a system-defined layout file that displays only one line of text, a data source (a list collection). At the same time use Setadapter () to complete the final work of adaptation. The actual structure after operation is as follows:

Simplecursoradapter

The SDK explains this: an easy adapter to map columns from a cursor to textviews or imageviews defined in an XML file. You can specify which columns your want, which views you want to display the columns, and the XML file that defines the app Earance of these views. Simply put, it is convenient to display the data from the cursor, and can map the specified column to the corresponding TextView.

The following program displays the contacts from the phone book to the class table. Add a contact as a database data in your contacts first. Then get a cursor to the database and define a layout file (you can also use the system itself, of course).

12345678910111213141516171819202122232425262728 /** * @author allin * */public classMyListView2 extendsActivity {    privateListView listView;    //private List<String> data = new ArrayList<String>();    @Override    publicvoidonCreate(Bundle savedInstanceState){        super.onCreate(savedInstanceState);                listView = newListView(this);                 Cursor cursor = getContentResolver().query(People.CONTENT_URI, null, null, null, null);        startManagingCursor(cursor);                ListAdapter listAdapter = newSimpleCursorAdapter(this, android.R.layout.simple_expandable_list_item_1,                 cursor,                newString[]{People.NAME},                 newint[]{android.R.id.text1});                listView.setAdapter(listAdapter);        setContentView(listView);    }        }

cursor cursor = getcontentresolver (). query (People.content_uri, NULL, NULL, NULL), first get a cursor object pointing to the system Address Book database to get the data source.

Startmanagingcursor (cursor); The cursor object we will get is managed by the activity so that the cursor's life cycle and activity are automatically synchronized, eliminating the ability to manually manage the cursor.

Simplecursoradapter constructor The first 3 parameters are the same as the Arrayadapter, the last two arguments: A string array containing the database columns, and an int array containing the corresponding component IDs in the layout file. The effect is to automatically map each column of data represented by a string array to the component that corresponds to the ID of the layout file. The above code maps the data of the Name column once to the component with the ID of Text1 for the layout file.

Note: Required in androidmanifest.xml such as permissions: <uses-permission android:name= "Android.permission.READ_CONTACTS" ></ Uses-permission>

Post-run effects such as:

Simpleadapter

Simpleadapter is the best extensibility, you can define a variety of layouts, you can put on imageview (picture), you can also put a button (button), CheckBox (check box) and so on. The following code directly inherits the listactivity,listactivity and the normal activity is not much different, the difference is to display the ListView did a lot of optimization, the aspect shows just.

The following program implements a class table with a picture.

First you need to define the XML that good one uses to display the contents of each column

Vlist.xml

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "android:orientation=" horizontal "android:layout_width=" Fill_parent "android:layout_height=" Fill_parent " ><imageview android:id= "@+id/img" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Android:layout_margin= "5px"/><linearlayout android:orientation= "vertical" android:layout_width= "wrap_ Content "android:layout_height=" wrap_content "><textview android:id=" @+id/title "android:layout_width=" Wrap_ Content "android:layout_height=" wrap_content "android:textcolor=" #FFFFFFFF "android:textsize=" 22px "/>< TextView android:id= "@+id/info" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Android: Textcolor= "#FFFFFFFF" android:textsize= "13px"/></linearlayout></linearlayout>

Here is the implementation code:

/** * @author Allin * */public class MYLISTVIEW3 extends Listactivity {//private list<string> data = new ArrayList <String> (); @Overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 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}); Setlistadapter (adapter);} Private list<map<string, object>> GetData () {list<map<string, object>> List = new arraylist< Map<string, object>> (); map<string, object> map = new hashmap<string, object> (), Map.put ("title", "G1"), Map.put ("info", "Google 1"); Map.put ("img", R.DRAWABLE.I1); List.add (map); map = new hashmap<string, object> (); Map.put ("title", "G2"); map.put ("info", "Google 2"), Map.put ("img", R.drawable.i2), List.add (map), map = new hashmap<string, object> (), Map.put (" Title "," G3 "); Map.put (" info "," Google 3 "), Map.put (" img ", R.drawable.i3); List.add (map); return List;}} 

Each section of the list,list that uses Simpleadapter data is composed of generally hashmap corresponding to each row of the ListView. Each key-value data for the HashMap is mapped to the corresponding ID component in the layout file. Since the system does not have a corresponding layout file available, we can define a layout vlist.xml ourselves. To do the following, the new one simpleadapter parameter is: this, the layout file (vlist.xml), HashMap title and info,img. The component of the layout file is id,title,info,img. Each component of the layout file is mapped to each element of the HashMap, and the adaptation is done.

Operating effects such as:

ListView with Buttons

But sometimes the list is not only used for display purposes, but we can also add buttons to it. Add a button first to write an XML file with a button, and then naturally think of the above method to define an adapter, and then map the data to the layout file. But this is not the case, because the button is not mapped, even if you successfully use the layout file to show the button can not add the response of the button, then you need to study how the ListView is realistic, and you must rewrite a class to inherit baseadapter. The following example displays a button and a picture with two lines of words if the button is clicked, the row of the button will be deleted. And tell you exactly how the ListView works. The effect is as follows:

Vlist2.xml

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "android:orientation=" horizontal "android:layout_width=" Fill_parent "android:layout_height=" Fill_parent " ><imageview android:id= "@+id/img" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Android:layout_margin= "5px"/><linearlayout android:orientation= "vertical" android:layout_width= "wrap_ Content "android:layout_height=" wrap_content "><textview android:id=" @+id/title "android:layout_width=" Wrap_ Content "android:layout_height=" wrap_content "android:textcolor=" #FFFFFFFF "android:textsize=" 22px "/>< TextView android:id= "@+id/info" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Android: Textcolor= "#FFFFFFFF" android:textsize= "13px"/></linearlayout><button android:id= "@+id/view_btn" Android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:text= "@string/s_view_btn" Android:layout_grAvity= "Bottom|right"/></linearlayout> 

Program code:

/** * @author Allin * */public class MyListView4 extends Listactivity {private list<map<string, object>> MDat A; @Overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); mdata = GetData (); Myadapter adapter = new Myadapter (this); Setlistadapter (adapter);} Private list<map<string, object>> GetData () {list<map<string, object>> List = new arraylist< Map<string, object>> (); map<string, object> map = new hashmap<string, object> (), Map.put ("title", "G1"), Map.put ("info", "Google 1"); Map.put ("img", R.DRAWABLE.I1); List.add (map); map = new hashmap<string, object> (); Map.put ("title", "G2"); map.put ("info", "Google 2"), Map.put ("img", R.drawable.i2), List.add (map), map = new hashmap<string, object> (), Map.put (" Title "," G3 "), Map.put (" info "," Google 3 "), Map.put (" img ", R.drawable.i3); List.add (map); return list;} The logical @overrideprotected void Onlistitemclick (ListView L, View v, int position, Lon) after a selected item in the ListViewG ID) {LOG.V ("Mylistview4-click", (String) mdata.get (position). Get ("title")); /** * Click the button popup dialog box in the ListView */public void Showinfo () {new Alertdialog.builder (this). Settitle ("My ListView"). Setmessage (" Introduction ... "). Setpositivebutton (" OK ", new Dialoginterface.onclicklistener () {@Overridepublic void OnClick (dialoginterface dialog, int which) {}}). Show (); Public final class Viewholder{public ImageView img;public TextView title;public TextView info;public Button viewbtn;} public class Myadapter extends Baseadapter{private layoutinflater minflater;public myadapter (context context) { This.minflater = Layoutinflater.from (context);} @Overridepublic int GetCount () {//TODO auto-generated method Stubreturn mdata.size ();} @Overridepublic Object getItem (int arg0) {//TODO auto-generated method Stubreturn null;} @Overridepublic long getitemid (int arg0) {//TODO auto-generated method Stubreturn 0;} @Overridepublic view GetView (int position, view Convertview, ViewGroup parent) {Viewholder holder = null;if (Convertview = =NULL) {holder=new viewholder (); 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 ();} Holder.img.setBackgroundResource ((Integer) mdata.get (position). Get ("img")); Holder.title.setText ((String) Mdata.get (position). Get ("title")), Holder.info.setText ((String) mdata.get (position). Get ("info")); Holder.viewBtn.setOnClickListener (New View.onclicklistener () {@Overridepublic void OnClick (View v) {showinfo ();}}); return Convertview;}}}

The following will be a detailed explanation of the above code, the ListView at the beginning of the drawing, the system first called the GetCount () function, according to his return is worth to the length of the ListView (This is why the first figure in the beginning of the special list length), and then according to this length, Call GetView () to draw each row one by one. If your GetCount () return value is 0, the list will not show the same return 1, and only one row will be displayed.

When the system displays the list, first instantiate an adapter (this will instantiate the custom adapter). When you manually complete the adaptation, you must manually map the data, which requires overriding the GetView () method. This method is called when the system draws each row of the list. GetView () has three parameters, position indicates that the first line will be displayed, Covertview is the layout inflate from the layout file. We use the Layoutinflater method to extract the well-defined Vlist2.xml file into a view instance for display. The individual components in the XML file are then instantiated (the Simple Findviewbyid () method). This allows the data to be mapped to individual components. However, in order to respond to a click event, the button needs to be added a click Listener to capture the click event. Now that a custom ListView has been completed, let's go back and look at the process from a new perspective. System to draw the ListView, he first obtains the length of the list to be drawn, and then begins to draw the first line, how to draw it? Call the GetView () function. In this function, we first get a view (actually a viewgroup) and then instantiate and set up each component to show it. Well, finish drawing this line. Then draw the next line until the painting is finished. During the actual run, you will find that each row in the ListView has no focus, because the button robs the ListView of the focus, as long as the button is set to no focus in the layout file.

Operating effects such as:

SOURCE download

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.