Android RecyclerView Item 点击/长按 事件

Android 列表控件 RecyclerView

在实例化 Adapter 类前写 Item 的 点击/长按 事件逻辑

MainActivity.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
ScheduleView mRecyclerView;

private void initView()
{
mRecyclerView = findViewById(R.id.schedule);

// 项目点击监听
ScheduleAdapter.ItemClickListener itemClickListener = new ScheduleAdapter.ItemClickListener() {
@Override
public void onItemClick(View itemView) {
// 点击
}

@Override
public void onItemLong(View itemView) {
// 长按
}
};

mAdapter = new ScheduleAdapter(itemClickListener);
mRecyclerView.setAdapter(mAdapter); // adapter 应用到 RecyclerView
}

ScheduleAdapter.java

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
38
public class ScheduleAdapter extends RecyclerView.Adapter<ScheduleAdapter.ViewHolder>
{
private ItemClickListener mItemClickListener;

public ScheduleAdapter(ItemClickListener itemClickListener) {
mItemClickListener = itemClickListener;
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
if (!holder.itemView.hasOnClickListeners()) {
holder.itemView.setOnClickListener(mItemClickListener);
holder.itemView.setOnLongClickListener(mItemClickListener);
}
}

/**
* 点击监听
*/
public static class ItemClickListener implements View.OnClickListener, View.OnLongClickListener {
public void onClick(View v) {}
public boolean onLongClick(View v) { return true; }
}

/**
* View Holder
*/
public static class ViewHolder extends RecyclerView.ViewHolder {
public View itemView;

ViewHolder(View view) {
super(view);
itemView = view;
}
}

// ...
}
本站文章除注明转载外均为原创,未经允许不要转载哇. ヾ(゚ー゚ヾ) http://qwqaq.com/8bb3c5eb.html
分享到