如何在活动中访问onBindViewHolder的商品RecyclerView

时间:2019-10-17 23:37:12

标签: android android-activity android-recyclerview

我在recyclerView中设置了adapter.,使用interface来监听点击事件,这有助于我了解每个项目的位置和视图。

但是,我还需要访问array方法内的onBindViewHolder项。有没有办法我也可以使用该方法?

界面

public interface ItemClickListener {

    void onItemClick(View view, EpisodeAdapter.ViewHolder holder, int position);
}

适配器

 @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
    final Episode episode = postList.get(position);
        final String title = episode.getTitle();
        final Long timeStamp = postList.get(position).getTimestamp();
        holder.setTitle(title);
//how to make this method and items accessible by my activity
    }

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

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
        private View mView;
        private CardView mParent;
        private TextView mTitle, mMonth, mDate;
        public ViewHolder(View itemView) {
            super(itemView);
            mView = itemView;
            mTitle = mView.findViewById(R.id.title);
            mMonth = mView.findViewById(R.id.month);
            mDate = mView.findViewById(R.id.date);
            mParent = mView.findViewById(R.id.parentView);
            itemView.setOnClickListener(this);
        }

        public void setTitle(String text){
            mTitle = mView.findViewById(R.id.title);
            mTitle.setText(text);
        }
        public void setDate(String text){
            mDate = mView.findViewById(R.id.date);
            mDate.setText(text);
        }
        public void setMonth(String text){
            mMonth = mView.findViewById(R.id.month);
            mMonth.setText(text);
        }


        @Override
        public void onClick(View v) {
            if (itemClickListener != null) {
                itemClickListener.onItemClick(v,  getAdapterPosition());
            }
        }
    }

    private ItemClickListener itemClickListener;

    public void setOnItemClickListener(ItemClickListener mItemClickListener) {
        this.itemClickListener = mItemClickListener;
    }
}

活动

adapter.setOnItemClickListener((view, position) -> {
//only view and position available. how to access view holder items
            }

1 个答案:

答案 0 :(得分:0)

您可以更改ItemClickListener的签名,以支持将单击的项目传递给实现回调的类。尝试将侦听器更改为类似以下内容:

public interface ItemClickListener {
    void onItemClick(YourItem item);
}

当您覆盖onClick时,请执行

之类的操作来传递该项
@Override
public void onClick(View v) {
    if (itemClickListener != null) {
        itemClickListener.onItemClick(postList.get(position));
    }
}

您可以在此处找到有关此技术的更多信息:https://antonioleiva.com/recyclerview-listener/