Android ListView details

Source: Internet
Author: User

Since google doc cannot be opened by many people, the source code [Source Code download] ----

In android development, ListView is a commonly used component that displays specific content in the form of a list and can be automatically displayed based on the length of data. Sort out the usage of ListView and write a small example, for example.

The display of the list requires three elements:

1. ListVeiw is used to display the View of the list.

2. the adapter is used to map data to the mediation on the ListView.

3. The specific string, image, or basic component of the data to be mapped.

Based on the list of adapter types, the list is divided into three types: ArrayAdapter, SimpleAdapter, and SimpleCursorAdapter

ArrayAdapter is the simplest and can only display one line of words. SimpleAdapter has the best scalability and Can Customize various effects. SimpleCursorAdapter can be considered as a simple combination of SimpleAdapter on the database. It can display the database content in the form of a list.

We start with the simplest ListView:

/*** @ Author allin **/public class MyListView extends Activity {private ListView listView; // private List <String> data = new ArrayList <String> (); @ Overridepublic void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); listView = new ListView (this); listView. setAdapter (new ArrayAdapter <String> (this, android. r. layout. simple_expandable_list_item_1, getData (); setContentView (listView);} private List <String> getData () {List <String> data = new ArrayList <String> (); data. add ("test data 1"); data. add ("Test data 2"); data. add ("Test data 3"); data. add ("test data 4"); return data ;}}

The preceding Code uses ArrayAdapter (Context context, int textViewResourceId, List <T> objects) to assemble data, to assemble the data, you need an adapter connecting the ListView view object and the array data to adapt the two. The ArrayAdapter structure requires three parameters: this, layout file (note that the layout file here describes the layout of each row in the list, android. r. layout. simple_list_item_1 is a layout file defined by the system that only displays one line of text, a data source (a List set ). At the same time, use setAdapter () to complete the final work of adaptation. The actual structure after running is as follows:

SimpleCursorAdapter

The sdk is interpreted as follows: An easy adapter to map columns from a cursor to TextViews or ImageViews defined in an XML file. you can specify which columns you want, which views you want to display the columns, and the XML file that defines the appearance of these views. Simply put, the data obtained from the cursor is displayed in the list and the specified columns can be mapped to the corresponding TextView.

The following program displays contacts in the phone book to the class table. Add a contact to the address book as the database data. Then obtain a Cursor pointing to the database and define a layout file (you can also use the built-in layout file ).

/** * @author allin * */public class MyListView2 extends Activity {private ListView listView;//private List<String> data = new ArrayList<String>();@Overridepublic void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);listView = new ListView(this);Cursor cursor = getContentResolver().query(People.CONTENT_URI, null, null, null, null);startManagingCursor(cursor);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);}}

Cursor cursor = getContentResolver (). query (People. CONTENT_URI, null); first obtain a Cursor object pointing to the system Address Book database to obtain the data source.

StartManagingCursor (cursor); The obtained Cursor object is managed by the Activity, so that the life cycle and Activity of the Cursor can be automatically synchronized, eliminating the need to manually manage the Cursor.

The first three parameters of the SimpleCursorAdapter constructor are the same as those of the ArrayAdapter. The last two parameters are: a String array containing the database columns and an int array containing the corresponding component id in the layout file. The function is to automatically map each column of data represented by the String array to the component with the corresponding id of the layout file. The code above maps the data in the NAME column to the component whose id is text1 in the layout file once.

Note: The permission in AndroidManifest. xml must be: <uses-permission android: name = "android. permission. READ_CONTACTS"> </uses-permission>

The effect after running is as follows:

SimpleAdapter

SimpleAdapter has the best scalability. It can define various la S, put ImageView, Button, and CheckBox. The following code directly inherits the ListActivity. There is no big difference between ListActivity and common Activity. The difference is that the display ListView has been optimized and displayed.

The following program implements a class table with images.

First, you must define an xml file to display the content 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>

The following 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;}}

Data Using simpleAdapter is generally a List composed of HashMap. Each section of the list corresponds to each row of the ListView. Each key-value data of HashMap is mapped to the component corresponding to the id in the layout file. Because the system does not have a corresponding layout file available, we can define a layout vlist. xml. Next we will make adaptation. The new SimpleAdapter parameter is: this, layout file (vlist. xml), HashMap title, info, img. The component id, title, info, and img of the layout file. The components of the layout file are mapped to the elements of HashMap to complete adaptation.

The running effect is as follows:

ListView with buttons

However, sometimes the list is not only used for display, we can also add a button on it. To add a button, you first need to write an xml file with a button. Then, you will naturally want to use the above method to define an adapter and map the data to the layout file. However, this is not the case because buttons cannot be mapped. Even if you have successfully displayed a button in the layout file, you cannot add a button response, in this case, we need to study how ListView is realistic and rewrite a class to inherit the BaseAdapter. The following example shows a button and an image. If you click a button, the row of the button is deleted. And tell you 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> mData; @ 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;} // logic after an item in ListView is selected @ Overrideprotected void onListItemClick (ListView l, View v, int position, long id) {Log. v ("MyListView4-click", (String) mData. get (position ). get ("title");}/*** click the button in the listview to bring up the dialog box */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 code above will be explained in detail below. When listView starts to be drawn, the system first calls the getCount () function, obtain the length of the listView Based on the returned value (this is why the list length is marked in the first figure at the beginning), and call getView () to draw each row one by one based on the length. If the returned value of getCount () is 0, the return 1 is not displayed in the list, and only one row is displayed.

When the system displays the list, an adapter is first instantiated (the custom adapter will be instantiated here ). When manual adaptation is completed, data must be manually mapped. You need to override the getView () method. This method is called when every row in the list is drawn. GetView () has three parameters. position indicates the row to be displayed, and covertView indicates the layout from the layout file. We use the LayoutInflater method to extract the defined vlist2.xml file into a View instance for display. Then, instantiate each component in the xml file (simple findViewById () method ). In this way, the data can be mapped to each component. However, to respond to a click event, you need to add a click listener for the button to capture the click event. So far, a custom listView is complete. Now let's look back at this process. The system wants to draw the ListView. He first obtains the length of the list to be drawn, and then begins to draw the first line. How can he draw it? Call the getView () function. In this function, first obtain a View (actually a ViewGroup), then instance and set each component to display it. Now, we have drawn this line. That

Draw the next line until the painting is complete. In the actual running process, it will be found that each row of the listView has no focus, because the Button grabs the focus of the listView, as long as the layout file sets the Button to no focus, it is OK.

The running effect is as follows:

Source code 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.