ListView是Android手机系统中使用非常频繁的控件,以垂直列表的形式显示数据项,ListView的用法也较为复杂,下面将详细介绍ListView相关的各种用法。
1、创建使用ListView
有2种方式创建ListView
- 在布局文件中使用ListView创建
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
在代码中获取到实例后为ListView设置Adapter
listView = (ListView)findViewById(R.id.list);
listView.setAdapter(adapter);
- Activity继承ListActivity
继承ListActivity后,不需要设置布局文件,直接使用setListAdapter()为ListView设置Adapter即可
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(adapter);
}
2、自定义ListView的item格式
新建布局文件item.xml,代码如下:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#F00"
android:textSize="16sp"/>
将文字设为居中显示,设置了文本的颜色和大小,构造Adapter时将布局文件传入
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.item, datas);
listView.setAdapter(adapter);
3、设置ListView的点击事件
为ListView的item设置点击事件
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "Item " + datas.get(position) + " clicked", Toast.LENGTH_LONG).show();
}
});
运行程序,点击列表项
4、ListView数据改变,更新ListView
修改ListView的点击事件,点击item后删除List中的数据项,数据改变后,页面不会自动刷新,需要调用adapter的notifyDataSetChanged()方法通知列表更新
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "Item " + datas.get(position) + " deleted", Toast.LENGTH_LONG).show();
datas.remove(position);
adapter.notifyDataSetChanged();
}
});
运行程序,点击任意列表项
5、ListView显示多种类型的item
上面的例子都是显示的一个类型的列表项,只包含一个TextView,有时会需要显示几种不同的item,包含图片、文本、按钮等元素,这就需要为ListView定义几个不同的布局文件,一个布局文件代表一种类型的item
布局文件item1.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:src="@drawable/ic_launcher"/>
<TextView
android:layout_width=