加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 07:36:11 所属栏目:Java 来源:网络整理
导读:我已经了解到,为了最大限度地提高 Android列表视图的效率,您应该只需要尽可能多的充满“行”视图,以适应屏幕.一旦视图移出屏幕,您应该在getView方法中重用它,检查convertView是否为null. 但是,当您需要2个不同的列表布局时,如何实现这个想法?让我们说它的订
我已经了解到,为了最大限度地提高 Android列表视图的效率,您应该只需要尽可能多的充满“行”视图,以适应屏幕.一旦视图移出屏幕,您应该在getView方法中重用它,检查convertView是否为null.

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

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

解决方法

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

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

在getView()中包含getItemViewType(),如下所示:

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,false);
    // etc,etc...

在谷歌会谈中观看Android的Romain Guy discuss the view recycler.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读