我正在尝试在Recycler视图中使用“按项目”单击侦听器,但是当我单击项目时,即使编译时没有错误,也不会发生任何事情,因此我输入了Breakpoints,这表明侦听器始终为null即使他是在Adapter构造函数中初始化的。 我正在关注本教程https://antonioleiva.com/recyclerview-listener/
1。在适配器中:
`公共类MyAdapter扩展了RecyclerView.Adapter {
private List<Device> devices;
private OnItemClickListener listener;
public MyAdapter(List<Device> devices, OnItemClickListener listener) {
this.devices = devices;
this.listener = listener;
}
...
public interface OnItemClickListener {
void onItemClick(Device device);
}`
2。在视图Holder中:
`void display(Device device,MyAdapter.OnItemClickListener listener){//方法绑定
itemView.setOnClickListener( v ->
listener.onItemClick( device ) );
...`
3。在主要活动中:
RecyclerView.setAdapter( new MyAdapter( devices, item ->
Toast.makeText( getContext(), "Item Clicked", Toast.LENGTH_LONG ).show()
) );
当我单击项目时,我必须烤面包