2

在我的Android应用程序中,我有包含汽车列表的ListView。每辆车都有(1至10)组的列表。如何在列表适配器中正确使用ViewHolder和自定义视图

在每个列表项中我都有水平的组列表。我在这个水平列表中使用FlowLayout,为此添加了“手动”视图。

林不知道我使用这个ViewHolder概念是完全错误的吗?

至少这比每个项目(FlowLayout)内部的水平列表都要消耗更多的内存。

我应该有自己的列表适配器这个水平列表,或者如何改善这个?

/** 
* List adapter (BaseAdapter), getView 
* 
*/ 
@Override 
public View getView(int position, View convertView, ViewGroup parent) { 

    ViewHolder holder = null; 
    Car car = (Car) getItem(position); 

    if (convertView == null) { 
     convertView = mInflater.inflate(R.layout.list_item_cars, null); 
     holder = new ViewHolder(); 
     holder.carName = (TextView)convertView.findViewById(R.id.car_name); 
     holder.carGroups = (FlowLayout)convertView.findViewById(R.id.car_groups); 
     convertView.setTag(holder); 
    } 
    else { 
     holder = (ViewHolder)convertView.getTag(); 
    } 

    holder.carName.setText(car.getName()); 
    buildGroupsFlowLayout(holder.carGroups, car.getGroups()); 
    return convertView; 
} 

/** 
* Build FlowLayout 
*/ 
private void buildGroupsFlowLayout(FlowLayout flowLayout, List<CarGroup> groupsList) { 

    flowLayout.removeAllViews(); 
    int i = 0; 

    for(CarGroup group : groupsList) { 
     View groupItemView = mInflater.inflate(R.layout.car_group_item, null); 
     TextView lineView = (TextView)groupItemView.findViewById(R.id.car_group_item_goup_text); 
     lineView.setText(group.getName()); 
     lineView.setTextColor(group.getColor()); 

     flowLayout.addView(groupItemView, i, new FlowLayout.LayoutParams(FlowLayout.LayoutParams.WRAP_CONTENT, FlowLayout.LayoutParams.WRAP_CONTENT)); 
     i++; 
    } 
} 

public static class ViewHolder { 
    public TextView carName; 
    public FlowLayout carGroups; 
} 
+0

对于这样的任务,'RecyclerView' +'GridLayoutManager'用自己的适配器,而不是'FlowLayout'可能会更好。 – aeracode

回答

0

尝试为其中的所有UI逻辑创建自定义视图(如CarView),然后将其用作ViewHolder。

也许是这样的:

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    CarView carView; 
    if(convertView == null){ 
     carView = new CarView(context); 
    } else { 
     carView = (CarView) convertView; 
    } 
    carView.setData(getItem(position)); 
    return carView; 
} 

而且Carview会(你可以把你在这里逻辑的FlowLayout):

public class CarView extends FrameLayout{ 

    public SeriesTileView(Context context) { 
    this(context, null); 
    } 

    public SeriesTileView(Context context, AttributeSet attrs) { 
    this(context, attrs, 0); 
    } 

    public SeriesTileView(Context context, AttributeSet attrs, int defStyleAttr) { 
    super(context, attrs, defStyleAttr); 
    inflate(context, R.layout.view_car, this); 
    findViews(); 
    } 

    public void setData(Car car) { 
    nameTextView.setText(car.getName()); 
    } 

} 
+0

我想这不会改变很多,与我原来的实施相比? – devha

相关问题