本文实例讲述了Android编程之控件ListView使用方法。分享给大家供大家参考。具体分析如下:
控件ListView是一个重要的控件,可以被用作用户列表等显示,下面进行它的操作测试。
下面代码实现了生成了一个ListView显示,并对每个条目的单击事件作出响应.
源代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
package com.list;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class ListTest extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<HashMap<String, Object>> users = new ArrayList<HashMap<String, Object>>();
for ( int i = 0 ; i < 20 ; i++) {
HashMap<String, Object> user = new HashMap<String, Object>();
user.put( "img" , R.drawable.icon);
user.put( "username" , "姓名(" + i+ ")" );
user.put( "age" , ( 20 + i) + "" );
users.add(user);
}
SimpleAdapter saImageItems = new SimpleAdapter( this ,
users, // 数据来源
//R.layout.user,//每一个user xml 相当ListView的一个组件
R.layout.user_layout, //每一个user xml 相当ListView的一个组件
new String[] { "img" , "username" , "age" },
// 分别对应view 的id
new int [] { R.id.img, R.id.name, R.id.age });
//获取适配器
ListView listView = (ListView) findViewById(R.id.users);
listView.setAdapter(saImageItems);
listView.setOnItemClickListener( new OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent,View view, int position, long id)
{
ListView listView = (ListView) parent;
Log.v( "Test" , "id = " + id + "(" + listView.getItemAtPosition(position).toString() + ")" );
}
});
/*
listView.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent,View view,int position,long id)
{
ListView listView = (ListView) parent;
Log.v("Test", "id = " + id + "("+ listView.getItemAtPosition(position).toString() + ")");
}
@Override
public void onNothingSelected(AdapterView<?> parent)
{
// TODO Auto-generated method stub
}
});
*/
}
}
|
效果图:
希望本文所述对大家的Android程序设计有所帮助。