2015-03-16 | learn

RecyclerView 实现 OnItemClickListener

新的 widget RecyclerView 不知出于什么样的考虑并没有像 ListView 那样提供 OnItemClickListener 需要自己来实现。 我想到了这个方法来实现。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
//XxxRecyclerViewAdapter.java
...
private OnItemClickListener onItemClickListener = null;

public interface OnItemClickListener {
onItemClick(View v, int p);
}




//ViewHolder实现中
public final class ListHolder
extends RecyclerView.ViewHolder {

public ListHolder(View itemView) {
super(itemView);

itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (onItemClickListener != null) {
onItemClickListener.onItemClick(v, getPosition());
}
}
});
}

}

public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
...



使用时只要为 adapter 设置 OnItemClickListener 就好了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//实现文件
private XxxRecyclerViewAdapter adaoter;

void init() {
...
view.setAdapter(adapter);
this.adapter.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
//do something...
}
});

...
}

总算是实现了功能 ^_^