1.在Adapter中定义监听接口
public class DeviceListAdapter extends RecyclerView.Adapter<DeviceViewHolder> {public interface OnItemClickListener {public void onItemClick(View view, int position);public void onItemLongClick(View view, int position);}private OnItemClickListener mOnItemClickListener;public void setOnItemClickListener (OnItemClickListener onItemClickListener) {this.mOnItemClickListener = onItemClickListener;}可以在onBindViewHolder()方法中设置每项的监听@Overridepublic void onBindViewHolder(@NonNull DeviceViewHolder holder, int position) {holder.itemView.setOnClickListener(v -> {if (mOnItemClickListener != null) {mOnItemClickListener.onItemClick(v, holder.getAdapterPosition());}});holder.itemView.setOnLongClickListener(v -> {if (mOnItemClickListener != null) {mOnItemClickListener.onItemLongClick(v, holder.getAdapterPosition());}});}}
2.在Activity或者Fragment中设置监听
adapter.setOnItemClickListener(new DeviceListAdapter.OnItemClickListener() {@Overridepublic void onItemClick(View view, int position) {Toast.makeText(requireActivity(), "onItemClick position = "+position, Toast.LENGTH_SHORT).show();}@Overridepublic void onItemLongClick(View view, int position) {Toast.makeText(requireActivity(), "onItemLongClick position = "+position, Toast.LENGTH_SHORT).show();}});mBinding.deviceListRv.setAdapter(adapter);