首页 > 代码库 > ListView用法详解

ListView用法详解

public void setAdapter (ListAdapter adapter)

常用ListAdapter包括:

BaseAdapter:常用于被扩展,继承BaseAdapter,大数据量时,采用缓存复用,会大大减少内存使用,提高效率。

@Override        //定义ListView的数据的长度,必须修改此项否则,默认为0,不生成任何列表项	public int getCount() {		// TODO Auto-generated method stub		return personList.size();	}        //获得适配器中指定位置的列表项。	@Override	public Object getItem(int arg0) {		// TODO Auto-generated method stub		return null;	}        //得到与列表中指定位置相关的行ID	@Override	public long getItemId(int arg0) {		// TODO Auto-generated method stub		return 0;	}        /**         * 此方法返回的是ListView的列表中某一行的View对象	 * position 当前返回的view的索引位置	 * convertView 缓存对象	 * parent 就是ListView对象	 */	@Override	public View getView(int arg0, View arg1, ViewGroup arg2) {                        View view = null;						if(convertView == null) {				// 布局填充器对象, 用于把xml布局转换成view对象				LayoutInflater inflater = MainActivity2.this.getLayoutInflater();				view = inflater.inflate(R.layout.listview_item, null);				Log.i(TAG, "getView: 新建" + position);			} else {				view = convertView;				Log.i(TAG, "getView: 复用缓存" + position);			}						// 给view中的姓名和年龄赋值			TextView tvName = (TextView) view.findViewById(R.id.tv_listview_item_name);			TextView tvAge = (TextView) view.findViewById(R.id.tv_listview_item_age);						Person person = personList.get(position);						tvName.setText("姓名: " + person.getName());			tvAge.setText("年龄: " + person.getAge());			return view;	}                    

SimpleAdapter

List<Map<String, Object>> data = http://www.mamicode.com/new ArrayList>();"name", "张三1");		map.put("icon", R.drawable.f007);		data.add(map);				map = new HashMap<String, Object>();		map.put("name", "张三2");		map.put("icon", R.drawable.f007);		data.add(map);		map = new HashMap<String, Object>();		map.put("name", "张三3");		map.put("icon", R.drawable.f007);		data.add(map);		map = new HashMap<String, Object>();		map.put("name", "张三4");		map.put("icon", R.drawable.f007);		data.add(map);		map = new HashMap<String, Object>();		map.put("name", "张三5");		map.put("icon", R.drawable.f007);		data.add(map);
SimpleAdapter adapter = new SimpleAdapter(				this, // 上下文				data, // listView绑定的数据				R.layout.listview_item, // listview的子条目的布局的id				new String[]{"name", "icon"}, 	// data数据中的map集合里的key				new int[]{R.id.tv_name, R.id.iv_icon}); // resource 中的id				mListView.setAdapter(adapter);

ArrayAdapter

               String[] textArray = {"功能1","功能2","功能3","功能4","功能5","功能6","功能7","功能8"};                 /*		 * 定义数据适配器		 * android.R.layout.simple_list_item_1  Listview的子条目显示的布局的id		 * textArray 显示在ListView列表中的数据		 */		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, 				android.R.layout.simple_list_item_1, 				textArray);				mListView.setAdapter(adapter);                

  

ListView用法详解