我一直在学习Commonsware Android编程教程,在第5个教程的额外挑战2中,要求根据对象的“类型名称”(餐厅的“类型”属性,即字符串)使用多个布局来显示ListView中的行。因此,它建议在自定义ArrayAdapter中重写getItemViewType和getViewTypeCount。此外,android文档和其他在线教程或博客文章也提出了同样的建议。
在这种情况下,遵循此方法并覆盖这两种方法可以正常工作,但会导致基于检查餐厅“类型”属性的值而产生重复逻辑。例如(请注意,此适配器是内部类,restaurants是声明为外部Activity成员的Restaurant对象的ArrayList):
我困扰的是重复的逻辑(在
这样做实现了动态加载三个xml布局的目标,消除了冗余逻辑,略微减少了代码对布局数量的耦合,并且不需要覆盖getViewTypeCount和getItemViewType方法。
我的问题是:如果不必要,为什么要覆盖这两个方法?
在这种情况下,遵循此方法并覆盖这两种方法可以正常工作,但会导致基于检查餐厅“类型”属性的值而产生重复逻辑。例如(请注意,此适配器是内部类,restaurants是声明为外部Activity成员的Restaurant对象的ArrayList):
class RestaurantsAdapter extends ArrayAdapter<Restaurant> {
private static final int ROW_TYPE_DELIVERY = 0;
private static final int ROW_TYPE_TAKE_OUT = 1;
private static final int ROW_TYPE_SIT_DOWN = 2;
RestaurantsAdapter() {
super(LunchListActivity.this, android.R.layout.simple_list_item_1, restaurants);
}
public int getViewTypeCount() {
return 3;
}
public int getItemViewType(int position) {
String type = restaurants.get(position).getType();
if (type == "delivery") {
return ROW_TYPE_DELIVERY;
} else if (type == "take_out") {
return ROW_TYPE_TAKE_OUT;
} else {
return ROW_TYPE_SIT_DOWN;
}
}
// Sets the icon, name and address of the Restaurant for the view.
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
RestaurantHolder viewHolder;
if (row == null) {
LayoutInflater inflater = getLayoutInflater();
switch (getItemViewType(position)) {
case ROW_TYPE_DELIVERY:
row = inflater.inflate(R.layout.row_delivery, null);
break;
case ROW_TYPE_TAKE_OUT:
row = inflater.inflate(R.layout.row_take_out, null);
break;
default:
row = inflater.inflate(R.layout.row_sit_down, null);
break;
}
viewHolder = new RestaurantHolder(row);
row.setTag(viewHolder);
} else {
viewHolder = (RestaurantHolder)row.getTag();
}
viewHolder.populateFrom(restaurants.get(position));
return row;
}
}
我困扰的是重复的逻辑(在
getItemViewType
中的if/else和getView
中的switch
)。因此,我将我的实现更改为以下内容:class RestaurantsAdapter extends ArrayAdapter<Restaurant> {
RestaurantsAdapter() {
super(LunchListActivity.this, android.R.layout.simple_list_item_1, restaurants);
}
// Sets the icon, name and address of the Restaurant for the view.
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
RestaurantHolder viewHolder;
if (row == null) {
LayoutInflater inflater = getLayoutInflater();
if (restaurants.get(position).getType() == "delivery") {
row = inflater.inflate(R.layout.row_delivery, null);
} else if (restaurants.get(position).getType() == "take_out") {
row = inflater.inflate(R.layout.row_take_out, null);
} else {
row = inflater.inflate(R.layout.row_sit_down, null);
}
viewHolder = new RestaurantHolder(row);
row.setTag(viewHolder);
} else {
viewHolder = (RestaurantHolder)row.getTag();
}
viewHolder.populateFrom(restaurants.get(position));
return row;
}
}
这样做实现了动态加载三个xml布局的目标,消除了冗余逻辑,略微减少了代码对布局数量的耦合,并且不需要覆盖getViewTypeCount和getItemViewType方法。
我的问题是:如果不必要,为什么要覆盖这两个方法?