gpt4 book ai didi

android - 具有多行 View 的自定义适配器中的 convertView

转载 作者:行者123 更新时间:2023-11-29 00:21:43 25 4
gpt4 key购买 nike

我正在实现自定义适配器,它根据这个(非常有用的)教程在 listview 中处理多种类型的行:http://logc.at/2011/10/10/handling-listviews-with-multiple-row-types/

现在,我以为我明白了一切,但有一件事让我感到困惑。在 getView 方法中,我们接收到 convertView,它假设是具有特定布局的 View (组),以显示在 ListView 的特定行中。

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 中有多种类型的行(例如,带有分隔行的动物列表,标题为“哺乳动物”、“鱼”、“鸟”)如何listview 知道要发送什么 convertView 吗?它可以是两种完全不同的类型之一。我不太清楚。有人可以解释一下吗?

最佳答案

来自您提供的教程:)

android 适配器提供的用于管理不同行类型的两个额外方法是:

getItemViewType(int position)getViewTypeCount()。 ListView 使用这些方法创建不同的 View 池以重用不同类型的行。

祝你好运:)

关于android - 具有多行 View 的自定义适配器中的 convertView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22534117/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com