控件ListView是一个重要的控件,可以被用作用户列表等显示,下面进行它的操作测试。
下面代码实现了生成了一个ListView显示,并对每个条目的单击事件作出响应.
源代码:
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 } }); */ } }效果图: