ListView继承AbsListView,而AbsListView是一个抽象类,其继承父类AdapterView
创建ListView有2中方法:
1.直接使用ListView
2.让Activity继承ListActivity
一旦程序或得ListView后,只要调用setAdapter(Adapter)即可
实现ListView的Adapter通常有四种:
1、ArrayAdapter:简单、易用的Adapter,通常用于数组或者List集合的多个值包装成多个列表项。
2、SimpleAdapter:并不简单、功能强大的Adapter,用于将List集合的多个对象包装成列表项。(常用)
3、SimpleCursorAdapter:与SimpleAdapter一样,只是用于Cursor提供的数据。
4、BaseAdapter:通常用于呗扩展,扩展BaseAdapter可以对各列表进行最大限度的定制(常用)
介绍SimpleAdapter的使用:
public class ListActivityTest extends Activity {
private String []names =new String[]{"张三", "李四","王五" ,"赵六" };
private String[] descs = new String[]{ "打麻将","打牌" ,"玩塞子" ,"玩牌九" };
private int [] imageIds = new int[]{R.drawable.a,R.drawable.b,R.drawable. c,R.drawable.d};
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout. activity_list);
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
for(int i =0;i<names.length;i++){
Map<String,Object> map = new HashMap<String, Object>();
map.put( "header", imageIds [i]);
map.put( "personName", names [i]);
map.put( "desc", descs [i]);
list.add(map);
}
//创建一个SimpleAdapter对象
//第一个参数是上下文对象,第二个参数是数据源,第三个是引用那个布局(每一条List的布局)
//第四个参数是从数据源里面得到那些数据,第五个参数是对应的哪个id,就会显示在哪个控件上
SimpleAdapter adapter = new SimpleAdapter(this, list,R.layout.list_adapter ,
new String[]{"header" ,"personName" ,"desc" },new int[]{R.id.header,R.id.name,R.id. desc});
ListView listView = (ListView)findViewById(R.id. mylist);
listView.setAdapter(adapter);
}
}
布局文件:acitvity_list
<?xml version="1.0" encoding= "utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ListView android:layout_width= "fill_parent"
android:layout_height="wrap_content"
android:id="@+id/mylist" ></ListView>
</LinearLayout>
布局文件二:list_adapter
<?xml version="1.0" encoding= "utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ImageView android:layout_width="80dp"
android:layout_height="80dp"
android:id="@+id/header"
android:paddingLeft="10dp"
android:scaleType="fitCenter" />
<LinearLayout android:layout_width= "match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dp"
android:textColor="#f0f"
android:paddingLeft="10dp"
android:id="@+id/name" />
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14dp"
android:textColor="#f0f"
android:paddingLeft="10dp"
android:id="@+id/desc" />
</LinearLayout >
</LinearLayout>