如何在更新

时间:2015-09-21 20:02:59

标签: android android-layout android-viewholder

RecyclerView ViewHolder我有一个RelativeLayout。在我的OnBindViewHolder方法中,我根据条件更新整个布局的高度和包含的ImageView。这样可以正常工作,但是,这种新布局正在为不符合条件的后续视图进行回收。因此,产生不一致的结果。

// Involves populating data into the item through holder
@Override
public void onBindViewHolder(RallyAdapter.ViewHolder viewHolder, final int position) {

    //Expand viewholder and thumbnail if rally name takes up multiple lines
    if(rally.getName().length() > 23) {

        RelativeLayout.LayoutParams relParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

        //Original height is 114
        relParams.height = 139

        //where 'relativeLayout' is referencing the base layout
        viewHolder.relativeLayout.setLayoutParams(relParams);

        RelativeLayout.LayoutParams imgParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        //Original height is 117
        imgParams.height = 143

        viewHolder.thumbnail.setLayoutParams(imgParams);
    } else {

        //Need code here to reset layout and thumbnail to original heights 
    }
}

我知道我必须对我的情况有所了解,因为我在onBindViewHolder函数中,但我不知道它应该是什么。

1 个答案:

答案 0 :(得分:3)

如果我要写这个。我可能会有两个不同高度的xml文件。然后我可以在适配器中使用getItemViewType()来判断哪个位置属于哪种类型。通过这种方式,回收者视图可以为您所在的每个位置回收正确的视图。(您无需重置每行的大小)

public class TestAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private final static int TYPE_1=1;
    private final static int TYPE_2=2;
    @Override
    public int getItemViewType(int position) {
        if(rally.getName().length() > 23) {
            return TYPE_1;
        }
        return TYPE_2;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int type) {
        View view = LayoutInflater.from(mContext).inflate(/** your layout **/)
        if (i == TYPE_1) {
           RelativeLayout.LayoutParams relParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, 139);
           RelativeLayout.LayoutParams imageParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, 143);
           viewHolder.relativeLayout.setLayoutParams(relParams);
           viewHolder.thumbnail.setLayoutParams(imgParams);
           return new RecyclerView.ViewHolder(/**View_height_139**/);
        }
           return new RecyclerView.ViewHolder(/**View_height_114**/);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
        if (viewHolder.getItemViewType() == TYPE_1) {
            // Do the binding for when rally.getName().length > 23
        } else {
            // Do the bindings for the rest
        }
    }

    @Override
    public int getItemCount() {
        return 10.;
    }
}