adapter的基本写法
1、写adapter类时,需要继承BaseAdapter类
2、基本上需要写构造函数
3、为了优化listview还需要用到viewholder的方式来保存控件
以下是一个示范性代码
public class Adapter extends BaseAdapter {
private Context context;
private List<String> list;
public Adapter(Context context,List<String> list){
this.context=context;
this.list=list;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
viewholder holder=null;
if(convertView==null){
holder=new viewholder();
convertView=LayoutInflater.from(context).inflate(R.layout.activity_ main, null);
holder.textView=(TextView)
convertView.findViewById(R.id.text);
convertView.setTag(holder);
}else{
holder=(viewholder) convertView.getTag();
}
holder.textView.setText(getItem(position).toString());
return convertView;
}
private static class viewholder{
private TextView textView;
}
}