ListView是Android经常用到的控件,它用来展示可以滚动的列表。ListView里的列表项是通过adapter来添加的,adapter必须是继承“BaseAdapter”,它的职责是提供数据模型,以及把数据转换成列表项。
Android自带ArrayAdapter、SimpleAdapter和CursorAdapter
ArrayAdapter处理数组或者列表里的数据,通常列表项只有一个文本。
CursorAdapter主要针对数据使用。
SimpleAdapter处理列表里的数据,不同于ArrayAdapter,SimpleAdapter每一个列表项由一个Map对象提供数据。
SimpleAdapter实现ListView的步骤:
1. 定义列表项的layout
2. 准备ListView要显示的数据 ;
3. 把数据添加到数组里;
4. 构建适配器 , 数据适配器 , 动态数组有多少元素就生成多少个列表项;
5. 把适配器 添加到ListView,并显示出来。
1.定义列表项的layout,某一项的layout,并不是整个List的layout。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="horizontal"> <TextView android:text="TextView" android:id="@+id/accountType" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingLeft="10pt" android:background="#FFFFFF" android:width="30pt"></TextView> <TextView android:text="TextView" android:id="@+id/accountNumber" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingLeft="10pt" android:background="#FFFFFF" android:width="60pt"></TextView> <TextView android:text="TextView" android:id="@+id/password" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingLeft="10pt"></TextView> </LinearLayout> |
AccountsActivity
package com.eightqiu.secretbox; import java.util.ArrayList; import java.util.HashMap; import android.app.Activity; import android.os.Bundle; import android.widget.ListView; import android.widget.SimpleAdapter; public class AccountsActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.passwords); ListView listView = (ListView) findViewById(R.id.list_view_passwords); ArrayList<HashMap<String, String>> accountInfos = getAccountInfos(); // 4. 构建适配器 , 数据适配器 , 动态数组有多少元素就生成多少个列表项; SimpleAdapter simpleAdapter = new SimpleAdapter(this, accountInfos, R.layout.account_info_item, new String[] { "accountType", "accountNumber", "password" }, new int[] { R.id.accountType, R.id.accountNumber, R.id.password }); // 5. 把适配器 添加到ListView,并显示出来。 listView.setAdapter(simpleAdapter); } /** * 2.准备ListView要显示的数据; <br> * 3.把数据添加到数组里; **/ private ArrayList<HashMap<String, String>> getAccountInfos() { ArrayList<HashMap<String, String>> accountInfos = new ArrayList<HashMap<String, String>>(); HashMap<String, String> accountInfo1 = new HashMap<String, String>(); accountInfo1.put("accountType", "qq"); accountInfo1.put("accountNumber", "335373989"); accountInfo1.put("password", "132456"); HashMap<String, String> accountInfo2 = new HashMap<String, String>(); accountInfo2.put("accountType", "email"); accountInfo2.put("accountNumber", "dinglei@126.com"); accountInfo2.put("password", "132456"); accountInfos.add(accountInfo1); accountInfos.add(accountInfo2); return accountInfos; } } |