为什么我在点击商品时得到随机结果?我的错误是在btn onClick侦听器内部,但是在TextView(reference_number)中显示的内容很好。单击按钮时-它会打开另一个活动以显示有关该活动的更多详细信息,但它显示随机结果,当我滚动recyclerView后,它将再次更改结果。 @@ im已经很困惑,下面是我适配器中的所有代码
此错误的原因是什么,我在哪里弄错了?
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>{
int i;
@NonNull
@Override
public RecyclerViewAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_history_pending, parent, false);
return new ViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull RecyclerViewAdapter.ViewHolder holder, final int position) {
i = holder.getAdapterPosition();
holder.reference_number.setText("#"+mainActivity.myBookings.getCargoBooking().get(i).getReferenceNumber());
holder.btn_details.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String fee;
fee = isNull(mainActivity.myBookings.getCargoBooking().get(i).getCargoItem().get(0).getCargoFee().toString());
Intent i = new Intent(mainActivity.context, BookingDetailsActivity.class);
i.putExtra("fee", fee);
startActivity(i);
}
});
}
private String isNull(String s){
if (s != null){
return s;
} else return "";
}
@Override
public int getItemCount() {
return mainActivity.myBookings.getCargoBooking().size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView reference_number, driver_schedule;
Button btn_details;
public ViewHolder(View itemView) {
super(itemView);
reference_number = itemView.findViewById(R.id.tv_pending_trackNum);
driver_schedule = itemView.findViewById(R.id.tv_view_driver_schedule);
btn_details = itemView.findViewById(R.id.btn_pending_view);
}
}
}
答案 0 :(得分:1)
您的问题是适配器范围中的“ i”变量,将其删除并声明为本地变量(在onBindViewHolder方法内部),它应该可以工作。
答案 1 :(得分:0)
那是因为您的实例变量i
每次调用onBindViewHolder
时都会不断变化,例如滚动RecyclerView
时。而是将变量i
更改为local:
@Override
public void onBindViewHolder(@NonNull RecyclerViewAdapter.ViewHolder holder, final int position) {
final int i = holder.getAdapterPosition();