RecyclerView布局

文章目录
  1. RecyclerView获得行布局下标的两种方式
    1. 一.创建事件处理接口
    2. 二.创建适配器
      1. 说明:本篇文章主要说明获得行布局控件下标的两种方式,如果还有其他方式大家可以留言

RecyclerView获得行布局下标的两种方式

一.创建事件处理接口

1
2
3
4
5
public interface OnClickRecycler {

public void clickRecycler(int position);
public void longClickRecycler(int position);
}

二.创建适配器

说明:本篇文章主要说明获得行布局控件下标的两种方式,如果还有其他方式大家可以留言
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {

private List<Bean.T1348647853363Bean> beans;
private Context context;
private OnClickRecycler clickListener;

public RecyclerViewAdapter(Context context, List<Bean.T1348647853363Bean> beans){
this.beans = beans;
this.context = context;
}

public void setListener(OnClickRecycler clickListener){
this.clickListener = clickListener;
}

@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(context).inflate(R.layout.itemlayout,viewGroup,false);

MyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}

@Override
public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, final int i) {
Bean.T1348647853363Bean info = beans.get(i);
Glide.with(context).load(info.getImgsrc()).into(myViewHolder.imageView);
myViewHolder.textView.setText(info.getTitle());
myViewHolder.itemView.setTag(i);

//方式一:绑定时处理事件
myViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
clickListener.clickRecycler(i);
}
});

myViewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
clickListener.longClickRecycler(i);
return true;
}
});
}

@Override
public int getItemCount() {
return beans.size();
}

public class MyViewHolder extends RecyclerView.ViewHolder{

private TextView textView;
private ImageView imageView;

public MyViewHolder(@NonNull final View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.txt_item);
imageView = itemView.findViewById(R.id.img_item);

//方式二:ViewHolder类中实现事件处理,使用getTag()获得下标
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//itemView.getTag()返回绑定的下标
clickListener.clickRecycler((Integer) itemView.getTag());
}
});

itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
clickListener.longClickRecycler((Integer) itemView.getTag());
return true;
}
});
}
}
}