我正在制作一个健身应用程序,用户可以输入他/她所执行的代表数量和使用的重量。我正在使用recyclerview来进行可点击的数据输入。我可以使用相同的适配器来显示代表和重量但是如何区分是否选择了reps recyclerview项目或者是否选择了weight recyclerview项目。目前我正在为重量和代表使用单独的适配器,只有onclicklistener的差异。 这是代表和重量回收视图
以下是reps适配器的代码。除了监听器
之外,权重适配器是相同的public class RepsReelAdapter extends RecyclerView.Adapter<RepsReelAdapter.recyclerViewHolder> {
private LayoutInflater inflater;
private Context ctx;
List<NumReel> data = Collections.emptyList();
private RepsClickListener repsClickListener;
public RepsReelAdapter(Context context, List<NumReel> data){
inflater = LayoutInflater.from(context);
this.ctx = context;
this.data = data;
}
@Override
public recyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.number_row, parent, false);
return new recyclerViewHolder(view);
}
@Override
public void onBindViewHolder(recyclerViewHolder holder, int position) {
NumReel current = data.get(position);
holder.number.setText(String.valueOf(current.num));
}
@Override
public int getItemCount() {
return data.size();
}
class recyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView number;
public recyclerViewHolder(View itemView) {
super(itemView);
number = (TextView) itemView.findViewById(R.id.rnumber_tv);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(repsClickListener!=null){
repsClickListener.repsClick(v, getAdapterPosition());
}
}
}
public interface RepsClickListener{
void repsClick(View view, int position);
}
public void setRepsClickListener (RepsClickListener repsListener){
this.repsClickListener = repsListener;
}
以下是活动中点击的实现
@Override
public void repsClick(View view, int position) {
reps_num = repsReelAdapter.data.get(position).num;
}
答案 0 :(得分:1)
不是像onBindViewHolder那样在viewholder中设置onClickListener,而是
@Override
public void onBindViewHolder(recyclerViewHolder holder, int position) {
NumReel current = data.get(position);
holder.number.setText(String.valueOf(current.num));
holder.mView.setTag(current);
holder.mView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
NumReel dataAttachedToThisView = (NumReel) v.getTag();
// look at dataAttachedToThisView and decide if its weight or rep, then invoke
// respective methods
}
});
}
class recyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView number;
View mView;
public recyclerViewHolder(View itemView) {
super(itemView);
mView = itemView;
number = (TextView) itemView.findViewById(R.id.rnumber_tv);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(repsClickListener!=null){
repsClickListener.repsClick(v, getAdapterPosition());
}
}
}
每个适配器都可以包含相同数据类型的列表,因此您必须使用为对象提供视图的相同类模型。你可以做的是添加一个名为type的附加参数或使用inheritence