android中listview控件可以说是非常重要的控件,几乎每一个应用都会使用到它,例如游戏中的积分榜,音乐播放列表。但是,重要就意味着使用起来会有点繁琐,今天就来总结一下listview的使用步骤吧。
首先,使用listview要明确三个要素:
1.数据
2.适配器adapter
3.listview
然后,根据适配器的种类,我们可以把listview分成三种,有ArrayAdapter,SimpleAdapter和SimpleCursorAdapter,而最后一种是专门与数据库连接用的,今天先不讨论。
1.arrayadapter,这种是最简单的,不仅操作简单,显示也最简单。我们只需指定一个string数组就可以了,代码如下:
ListView buttonListView = (ListView)this.findViewById(R.id.typeListView);
String[] buttonArr = { mContext.getString(R.string.free_note),
mContext.getString(R.string.line_note),
mContext.getString(R.string.rect_note),
mContext.getString(R.string.triangle_note),
mContext.getString(R.string.round_note),
mContext.getString(R.string.highlight_note)
};
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(mContext,
android.R.layout.simple_expandable_list_item_1, buttonArr);
buttonListView.setAdapter(arrayAdapter);
2.simpleAdapter,这是使用最多的方式,因为你可以订制每个item的样式,较为繁琐。
步骤如下:
(1)创建一个List<Map<String,Object>>实例,再往该list里面添加一个个的HashMap<String,Object>,这个就是listview所有的数据,代码如下:
final List<Map<String, Object>> filterItems = new ArrayList<Map<String, Object>>();
Map<String, Object> filterItem = new HashMap<String, Object>();
filterItem.put("filterName", "TAG");
filterItem.put("filterValue",
getResources().getString(R.string.choose_note_tag));
filterItems.add(filterItem);
……
(2)创建simpleAdapter实例,为其制定数据和每个item的样式,这一步最为重要,代码如下:
SimpleAdapter simpleAdapter = new SimpleAdapter(this, filterItems,
R.layout.filter_item, new String[] { "filterName",
"filterValue" }, new int[] { R.id.filterName,
R.id.filterValue });
现在讲一下构造函数里面每个参数的含义吧:第一个是context,与一般的view一样,第二个是List,就是listview的数据项,第三个是item对应的布局文件,第四个是item中所有key的数组,第五个是item对应布局文件所有控件id的数组,必须与第四个参数一一对应。R.layout.filter_item布局文件如下:
<?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="vertical" >
<TextView
android:id="@+id/filterName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FF0" />
<TextView
android:id="@+id/filterValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
(3)最后,肯定是为Listview绑定adapter并显示,代码如下:
filterListView.setAdapter(simpleAdapter);
至此,listview的显示就完成了。
下面讲一下listview的事件响应,有itemlongclick和itemclick,大同小异,这里主要讲itemclick。
很简单添加监听器就ok了,但要记住onitemclick每个参数的意义,代码如下:
filterListView.setOnItemClickListener(new OnItemClickListener() {
/**
* arg0 noteListView的指针,可以通过它获取listview所有信息 arg1
* 点击的item的view的指针,可以获取item的id arg2 item的位置 arg3
* item在listview中的第几行,通常与arg2相同
*/
public void onItemClick(AdapterView<?> arg0, final View arg1,
int arg2, long arg3) {
}
最后,我们要注意,如果在onitemclick中修改listview某个item,一定要记住要修改adapter指定的list,不然如果屏幕朝向改变时,listview会重新绑定一次adapter,会造成显示原来的内容。