更新后如何将 RecyclerView ViewHolder 更改回原始布局

How to change RecyclerView ViewHolder back to original layout after updating

我有一个 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 
    }
}

我知道我必须对我的情况有一个 else,因为我在 onBindViewHolder 函数中,但我只是不知道它应该是什么。

如果我要写这个。我可能会有两个不同的 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.;
    }
}