我的RecyclerView
布局中有两个按钮,其中包含ID button1
和button2
。
这是我的RecyclerView
适配器:
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private Context context;
private List<Data> dataList;
public DataAdapter(Context context, List<Data> dataList) {
this.context = context;
this.dataList = dataList;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public Data data;
public Button button1, button2;
public ViewHolder(View v) {
super(v);
button1 = (Button) v.findViewById(R.id.button1);
button2 = (Button) v.findViewById(R.id.button2);
}
public void setData(Data data) {
this.data = data;
}
@Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.button1) {
clickButton(v);
}
}
}
@Override
public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.my_layout, parent, false);
return new ViewHolder(v);
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
final Data data = dataList.get(position);
holder.setData(data);
//
}
@Override
public int getItemCount() {
return dataList.size();
}
public void clickButton(View v) {
Button button1 = (Button) v;
// HOW DO I GET BUTTON2?
}
}
如何在button2
方法中获得clickButton()
,因为v
仅返回button1
的视图?
答案 0 :(得分:0)
您可以从点击侦听器本身传递两个按钮,如 -
clickButton(button1, button2);
原因是button1
,button2
是ViewHolder
类的成员变量,您实施了onClickListener
。
答案 1 :(得分:0)
您可以这样做:
@Override
public void onClick(View v) {
v.setTag(v.getId())
switch(v.getId()){
case R.id.button1:
clickButton(v);
break;
case R.id.button2:
clickButton(v);
break;
}
}
然后在clickButton方法中,只需获取标记并检查id以获取所需按钮并根据需要使用。