如何获取当前itemView行?

时间:2015-12-08 18:26:14

标签: android android-recyclerview

我有2个ViewHolders:用于默认和扩展(带有更多文本)。

当用户点击行时,它应该将其视图切换为扩展的视图。在下面的代码中,当我单击itemView时,每个itemView都会更改它的视图,而不仅仅是目标行。怎么办呢?感谢

private boolean isClicked;

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    int viewHoldertype = getItemViewType(position);

    Item item = items.get(position);
    holder.title.setText(item.getTitle());

    switch (viewHoldertype) {
        case TYPE_ARTICLE:

            holder.itemView.setOnClickListener((View v) -> {
                toggleItem();
            });
            break;
        case TYPE_EXPANDED_ARTICLE:
            final ExpandedViewHolder expandedItemHolder = (ExpandedViewHolder) holder;
            expandedItemHolder.description.setText(item.getDescription());
            expandedItemHolder.setIsRecyclable(false);
            expandedItemHolder.itemView.setOnClickListener((View v) -> {
                switch();
            });
            break;
    }
}

void switch() {
    isClicked = !isClicked;
    notifyDataSetChanged();
}

   class ViewHolder extends RecyclerView.ViewHolder {

    @Bind(R.id.image)
    ImageView image;
    @Bind(R.id.title)
    TextView title;

    public ViewHolder(View itemView) {
        super(itemView);
        itemView.setTag(this);
        ButterKnife.bind(this, itemView);
    }
}

class ExpandedViewHolder extends ViewHolder {

    @Bind(R.id.description)
    TextView description;

    public ExpandedViewHolder(View itemView) {
        super(itemView);
    }
}

1 个答案:

答案 0 :(得分:0)

在onBindViewHolder中设置OnClickListener时存储视图的位置,或者在onClick调用中通过RecyclerView.getChildPosition(view)获取当前位置。然后,您可以更改项目状态(展开它)并强制Recyclerview重绘所选项目。

@Override
public void onClick(final View view) {
    int itemPosition = mRecyclerView.getChildPosition(view);
    ...
}