继承BaseAdapter类
覆盖以下4个方法:
@Override public int getCount() { return users.size(); } @Override public Object getItem(int position) { return users.get(position); } @Override public long getItemId(int position) { return ((User)getItem(position)).getId(); } @Override public View getView(int position, View convertView, ViewGroup parent) { if(convertView==null){ convertView=inflater.inflate(resouce, null); } //获取相应控件 TextView id=(TextView) convertView.findViewById(R.id.user_id); TextView name=(TextView) convertView.findViewById(R.id.user_name); TextView phone=(TextView) convertView.findViewById(R.id.user_phone); User user= (User) getItem(position); //绑定数据 id.setText(String.valueOf(user.getId())); name.setText(user.getName()); phone.setText(user.getPhone()); return convertView; }
以上代码实现简单的ListView的适配器,
getCount()获取当前数据的总条数
getItem()根据POSITION获取具体能获取数据的对象
getItemId()根据POSITION获取具体能获取数据的ID
getView()根据POSITION和convertView得到绑定数据后的Item的View对象
对于其中的getView()方法可以涌过以下方式进行稍微优化:
public View getView(int position, View convertView, ViewGroup parent) { if(convertView==null){ convertView=inflater.inflate(resouce, null); //缓存控件对象 viewControl views=new viewControl(); views.id=(TextView) convertView.findViewById(R.id.user_id); views.name=(TextView) convertView.findViewById(R.id.user_name); views.phone=(TextView) convertView.findViewById(R.id.user_phone); convertView.setTag(views); } viewControl views= (viewControl) convertView.getTag(); User user= (User) getItem(position); views.id.setText(String.valueOf(user.getId())); views.name.setText(user.getName()); views.phone.setText(user.getPhone()); return convertView; } private final class viewControl{ public TextView id; public TextView name; public TextView phone; }
个人理解:
适配器其实就和计算机网络里的适配器一样,一种能揉和两种有一定关联却不能直接简单的接在一起的东西。在这里就是承担着将数据与控件绑定的功能。