具有自定义视图的ViewHolder模式重复列表视图

时间:2016-03-23 09:39:29

标签: android listview adapter

@Override
public View getView(int position, View convertView, ViewGroup parent) 
{
    ViewHolder holder;
    if ( convertView == null ) 
    {
        holder = new ViewHolder();
        View custView = new CustomView(false,  this.getItem(position), mContext, position).getView();
        holder.customView = custView;
        custView.setTag( holder );
    }
    else
    {
        holder = (ViewHolder) convertView.getTag();
        custView = holder.customView;
    }
    return custView ;   
}



private static class ViewHolder 
{
    View customView;
}

这是CustomView的一部分:

    public View getView() {
        return mDataViewRoot;
    }

    public CustomView(boolean cameFromA, CustomDataClass customDataObject, Context ctx, int position) {
        super();
        this.cameFromA= cameFromA;
        this.customDataObject= customDataObject;
        this.mContext = ctx;
        this.mPosition = position;
        LayoutInflater inflater = LayoutInflater.from(ctx);
        mDataViewRoot = inflater.inflate(R.layout.view_root, null);
        mViewsHolder = (LinearLayout) mDataViewRoot.findViewById(R.id.data_holder);
        determineState(source);
        prepareView();
        handleCornerArea();
    }

我想为性能(和更好的设计)原因实现一个视图持有者。 然而,它最终弄乱了我的列表,重复了视图..

1 个答案:

答案 0 :(得分:0)

我假设您在CustomView中设置视图数据。不要这样做,你需要在该适配器的getView方法中设置视图数据。

以下是使用视图持有者模式的正确方式:

web.config


编辑1:
如果您不想这样做,则必须将setter添加到CustomView并从getView方法调用它们。我想说的是你需要在getView方法中更新CustomView的数据,如果你没有,那么你得到的结果会发生什么......


编辑2:
您的视图持有者模式没有任何意义,您可以这样做:

@Override
public View getView(int position, View convertView, ViewGroup parent) 
{
    ViewHolder holder;
    if ( convertView == null ) {
        holder = new ViewHolder();
        // I don't know what you are doing with the boolean value, item or position...
        convertView = new CustomView(false,  this.getItem(position), mContext, position).getView();
        holder.mCustomViewsTextView = (TextView) convertView.findViewById(R.id.customTextView);
        convertView.setTag( holder );
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    holder.mCustomViewsTextView.setText = "Item position: " + position;

    return convertView;   
}

private static class ViewHolder {
    TextView mCustomViewsTextView;
    // Other views that are in your CustomView
    // ...
}