我在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
}
答案 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/