ListView的数据显示,三种适配器绑定方式
程序员文章站
2022-05-22 23:14:35
...
public void OnCreate(){ ... listView=(ListView)findViewById(R.id.listview); //点击条目的事件 listView.setOnItemClickListener(listener); show3(); } //点击条目的事件 private final class ItemClickListener implements OnItemClickListener{ public void OnItemClick(AdapterView<?>parent,View view,int position,long id){ ListView lv=(ListView)parent; //Person p=(Person)lv.getItemAtPosition(position);//调用自定义适配器,返回Person Cursor cursor=(Cursor)lv.getItemAtPosition(position);//SimpleCursorAdapter适配器 Toast.makeText(getApplicationContext(),p.Name,1).show(); } } //SimpleAdapter适配器 private void show(){ List<Person> persons=...; List<HashMap<String,Object>> data=new ArrayList<HashMap<String,Object>>(); for(Person p : persons){ HashMap<String,Object> item=new HashMap<String,Object>(); item.put("name",p.Name); item.put("phone",p.Phone); data.add(item); } SimpleAdapter adapter=new SimpleAdapter(this,data,R.layout.viewitem, new String[]{"name","phone"},new int[]{R.id.name,R.id.phone}); listview.setAdapter(adapter); /*int total=adapter.getCount(); int perpage=7; for(int i=0;i<perpage;i++){ View view=adapter.getView(i,convertView,parent); }*/ } //SimpleCursorAdapter适配器 private void show2(){ SimpleCursorAdapter adapter=new SimpleCursorAdapter(this,R.layout.viewitem,Cursor 对象, new String[]{"name","phone"},new int[]{R.id.name,R.id.phone}); listview.setAdapter(adapter) } //自定义适配器 private void show3(){ List<Person> persons=... PersonAdapter adapter=new PersonAdapter(this,persons,R.layout.viewitem); listView.setAdapter(adapter); } 自定义适配器 public class PersonAdapter extends BaseAdapter{ privte List<Person> persons;//要绑定的数据 private int resource;//绑定的条目的界面 LayoutInflater inflater;//布局填充器。生成所对应的view对象,系统内置 public PersonAdapter(Context context,List<Person> persons,int resource){ this.persons=persons; this.resource=resource; //取得系统内置的布局填充器 inflater=context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) } public int getCount(){ //得到要显示数据的总数 return persons.size(); } public Object getItem(int position){ //取得索引位置的值 return persons.get(position); } public long getItemId(int position){ //取得索引号 return position; } public View getView(int position,View convertView,ViewGroup parent){ TextView name=null; TextView phone=null; //取得条目的界面 if(convertView==null){ //第一页.不为null则重用它。不然每一次都生成一个view对象,则损耗性能 inflater.inflate(resource,null);//生成条目界面对象 name=convertView.findViewById(R.id.name); phone=convertView.findViewById(R.id.phone); ViewCache cache=new ViewCache(); cache.nameView=name; cache.phoneView=phone; convertView.setTag(cache);//标志,把缓存放进去。取得标志就可以取得缓存对象 }else{//不用去查找,重用以前生成的view ViewCache cache=(ViewCache)convertView.getTag(); name=cache.nameView; phone=cache.phoneView; } Person person=persons.get(position); //数据绑定 name.setText(person.Name); phone.setText(person.Phone); return converView; } //性能优化: //每显示一个条目,都会调用getView方法,如果每次都去查找显示控件,那影响性能 //定义一个内部类,用来缓存视图 private final class ViewCache{ public TextView nameView;//get,set更耗内存 public TextView phoneView; } }