2

我正在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”)如何listview知道convertView要发送什么?它可以是两种完全不同的类型之一。有些事情对我来说很不清楚。有人可以解释一下吗?

4

1 回答 1

2

从您提供的教程中:)

android Adapters 提供的另外两种管理不同行类型的方法是:

getItemViewType(int position)getViewTypeCount()。列表视图使用这些方法创建不同的视图池以重复用于不同类型的行。

祝你好运 :)

于 2014-03-20T13:32:10.300 回答