对于具有不同行布局模板的每个列表视图,我必须创建每个自定义适配器,它们执行相同的操作:加载 xml 行布局、通过 id 获取控制(TextView、ImageView 等)、显示数据......像这样:
public class CommentAdapter extends BaseAdapter {
protected Activity activity;
protected static LayoutInflater layoutInflater = null;
protected List<Comment> lst;
public CommentAdapter(Activity activity, List<Comment> lst){
this.activity = activity;
this.lst = lst;
layoutInflater = (LayoutInflater)this.activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return lst.size();
}
public Object getItem(int position) {
return lst.get(position);
}
public long getItemId(int position) {
return position;
}
public static class ViewHolder{
public TextView textName;
public TextView textComment;
public ImageView image;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder viewHolder;
if (v == null) {
v = layoutInflater.inflate(R.layout.listitem, null);
viewHolder = new ViewHolder();
viewHolder.textName = (TextView) v.findViewById(R.id.txtName);
viewHolder.image = (ImageView) v.findViewById(R.id.icon);
viewHolder.textComment = (TextView)v.findViewById(R.id.txtComment);
v.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) v.getTag();
}
Static.overrideFonts(v);
viewHolder.image.setBackgroundResource(lst.get(position).Icon);
viewHolder.textName.setText(lst.get(position).Name);
viewHolder.textComment.setText(lst.get(position).Comment);
return v;
}
}
对于多种列表视图(不同的行布局模板),我必须创建许多适配器。
所以,问题是我想创建一个模板适配器,它可以是动态加载行xml,基于其id的地图视图控件(可能使用反射)。行xml布局、控件id、视图控件将在其他地方定义。
有没有design pattern
,example
或者framework
可以做到这一点?