在具有 2 种不同布局的 Android Listview 中重用视图

我了解到,为了最大限度地提高Android列表视图的效率,您应该只拥有适合屏幕所需的膨胀“行”视图。将视图移出屏幕后,应在方法中重用它,检查是否为 null。getViewconvertView

但是,当您需要2个不同的列表布局时,如何实现这个想法?假设它是一个订单列表,1 个布局用于已完成的订单,另一个布局用于处理中的订单。

这是我的代码正在使用的想法的示例教程。在我的情况下,我将有2行布局:和R.layout.listview_item_product_completeR.layout.listview_item_product_inprocess

public View getView(int position, View convertView, ViewGroup parent) {

ViewHolder holder = null;

if (convertView == null) {
    holder = new ViewHolder();
    if(getItemViewType(position) == COMPLETE_TYPE_INDEX) {
        convertView = mInflator.inflate(R.layout.listview_item_product_complete, null);
        holder.mNameTextView = (TextView) convertView.findViewById(R.list.text_complete);
        holder.mImgImageView = (ImageView) convertView.findViewById(R.list.img_complete);
    }
    else { // must be INPROCESS_TYPE_INDEX
        convertView = mInflator.inflate(R.layout.listview_item_product_inprocess, null);
        holder.mNameTextView = (TextView) convertView.findViewById(R.list.text_inprocess);
        holder.mImgImageView = (ImageView) convertView.findViewById(R.list.img_inprocess);
    }
    convertView.setTag(holder);
} else {
    holder = (ViewHolder) convertView.getTag();
}
    thisOrder = (Order) myOrders.getOrderList().get(position);
    // If using different views for each type, use an if statement to test for type, like above
    holder.mNameTextView.setText(thisOrder.getNameValue());
    holder.mImgImageView.setImageResource(thisOrder.getIconValue());
    return convertView;
}

public static class ViewHolder {
    public TextView mNameTextView;
    public ImageView mImgImageView;
}

答案 1

您需要让适配器的视图回收器知道有多个布局,以及如何区分每行的两者。只需重写这些方法:

@Override
public int getItemViewType(int position) {
    // Define a way to determine which layout to use, here it's just evens and odds.
    return position % 2;
}

@Override
public int getViewTypeCount() {
    return 2; // Count of different layouts
}

合并内部 ,如下所示:getItemViewType()getView()

if (convertView == null) {
    // You can move this line into your constructor, the inflater service won't change.
    mInflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
    if(getItemViewType(position) == 0)
        convertView = mInflater.inflate(R.layout.listview_item_product_complete, parent, false);
    else
        convertView = mInflater.inflate(R.layout.listview_item_product_inprocess, parent, false);
    // etc, etc...

观看Android的Romain Guy在Google Talks上讨论视图回收器


答案 2

无需自己设计解决方案,只需覆盖 getItemViewType() 和 getViewTypeCount()。

有关示例 http://sparetimedev.blogspot.co.uk/2012/10/recycling-of-views-with-heterogeneous.html,请参阅以下博客文章

正如博客所解释的那样,Android实际上并不能保证getView会收到正确类型的视图。


推荐