我正在实现自定义适配器,它根据这个(非常有用的)教程处理listview
中的多种类型的行:http://logc.at/2011/10/10/handling-listviews-with-multiple-row-types/
现在,我以为我理解了一切,但有一件事困扰着我。 在getView方法中,我们收到convertView,它假定是具有特定布局的视图(组),以显示在列表视图的特定行中。
public View getView(int position, View convertView, ViewGroup parent) {
//first get the animal from our data model
Animal animal = animals.get(position);
//if we have an image so we setup an the view for an image row
if (animal.getImageId() != null) {
ImageRowViewHolder holder;
View view;
//don't have a convert view so we're going to have to create a new one
if (convertView == null) {
ViewGroup viewGroup = (ViewGroup)LayoutInflater.from(AnimalHome.this)
.inflate(R.layout.image_row, null);
//using the ViewHolder pattern to reduce lookups
holder = new ImageRowViewHolder((ImageView)viewGroup.findViewById(R.id.image),
(TextView)viewGroup.findViewById(R.id.title));
viewGroup.setTag(holder);
view = viewGroup;
}
//we have a convertView so we're just going to use it's content
else {
//get the holder so we can set the image
holder = (ImageRowViewHolder)convertView.getTag();
view = convertView;
}
//actually set the contents based on our animal
holder.imageView.setImageResource(animal.getImageId());
holder.titleView.setText(animal.getName());
return view;
}
//basically the same as above but for a layout with title and description
else {
DescriptionRowViewHolder holder;
View view;
if (convertView == null) {
ViewGroup viewGroup = (ViewGroup)LayoutInflater.from(AnimalHome.this)
.inflate(R.layout.text_row, null);
holder = new DescriptionRowViewHolder((TextView)viewGroup.findViewById(R.id.title),
(TextView)viewGroup.findViewById(R.id.description));
viewGroup.setTag(holder);
view = viewGroup;
} else {
view = convertView;
holder = (DescriptionRowViewHolder)convertView.getTag();
}
holder.descriptionView.setText(animal.getDescription());
holder.titleView.setText(animal.getName());
return view;
}
}
然而,如果listview
中有多种类型的行(例如,带有分隔符行的动物列表,如'mamals','fish','birds'),{{{ 1}}知道要发送的listview
是什么?它可以是两种完全不同的类型之一。我不清楚一些事情。有人可以解释一下吗?
答案 0 :(得分:2)
从您提供的教程中:)
android Adapters为管理不同行类型提供的另外两个方法是:
getItemViewType(int position)
和getViewTypeCount()
。
列表视图使用这些方法创建不同的视图池,以便为不同类型的行重用。
祝你好运:)