使用2种不同的布局重用Android Listview中的视图

时间:2012-11-08 20:30:27

标签: java android android-layout android-listview

我已经了解到,为了最大限度地提高Android列表视图的效率,您应该只需要在屏幕上显示所需数量的“行”视图。视图移出屏幕后,您应该在getView方法中重复使用该视图,检查convertView是否为空。

但是,当您需要2个不同的列表布局时,如何实现这个想法?让我们说它的订单列表和1个布局是针对已完成的订单而另一个布局是针对流程订单。

这是我的代码使用的想法的示例教程。就我而言,我会有两行布局: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;
}

2 个答案:

答案 0 :(得分:84)

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

@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...

在Google会谈中观看Android的Romain Guy discuss the view recycler

答案 1 :(得分:9)

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

有关示例http://sparetimedev.blogspot.co.uk/2012/10/recycling-of-views-with-heterogeneous.html

,请参阅以下博客文章

正如博客所解释的那样,Android实际上保证,getView将获得正确的视图类型。