RecyclerView显示一些正确项目之后的第一个项目。而且不正确的项目之一可能会多次更改自己的数据...这确实很奇怪,我不知道为什么,在另一个应用程序中,我编写了相同的代码,并且一切正常。我试图找到解决方法,但没有发现任何帮助。您可以观看视频以了解发生了什么。 video
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable
ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_car_list, container, false);
mRecyclerView = view.findViewById(R.id.car_recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
updateUI();
return view;
}
private class CarHolder extends RecyclerView.ViewHolder implements
View.OnClickListener {
private Car mCar;
public CarHolder(@NonNull final View itemView) {
super(itemView);
itemView.setOnClickListener(this);
mProducerTextView = itemView.findViewById(R.id.producerCardTextView);
mModelTextView = itemView.findViewById(R.id.modelCardTextView);
mPriceTextView = itemView.findViewById(R.id.priceCardTextView);
}
public void bind(Car car) {
mCar = car;
mProducerTextView.setText(getString(R.string.producer_params,
mCar.getProducer()));
mModelTextView.setText(getString(R.string.model_params,
mCar.getModel()));
mPriceTextView.setText(getString(R.string.price_params,
mCar.getPrice()));
}
@Override
public void onClick(View v) {
mListCallBack.onCarSelected(mCar);
}
}
private class CarAdapter extends RecyclerView.Adapter<CarHolder> {
private List<Car> mCars;
public CarAdapter(List<Car> cars) {
mCars = cars;
}
@NonNull
@Override
public CarHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
LayoutInflater inflater = LayoutInflater.from(getActivity());
View view = inflater.inflate(R.layout.list_item_car, viewGroup, false);
return new CarHolder(view);
}
@Override
public void onBindViewHolder(@NonNull CarHolder carHolder, int i) {
Car car = mCars.get(i);
carHolder.bind(car);
}
@Override
public int getItemCount() {
return mCars.size();
}
public void setCars(List<Car> cars) {
this.mCars = cars;
}
}
public void updateUI(){
List<Car> cars = CarLab.getCarLab(getActivity()).getCars();
if (mAdapter == null) {
mAdapter = new CarAdapter(cars);
mRecyclerView.setAdapter(mAdapter);
} else {
mAdapter.setCars(cars);
mAdapter.notifyDataSetChanged();
}
}
答案 0 :(得分:0)
也许您可以尝试使用以下方法来使RecyclerView不回收项目
:mRecyclerView.getRecycledViewPool().setMaxRecycledViews(0,0);
在onCreate()
下面的mRecyclerView.setLayoutManager(...)
方法中;
答案 1 :(得分:0)
当您使用字段变量mCar
(受所有绑定事件操纵)更新您的viewHoleder
时,仅使用传递给{{ 1}}来更新视图。
您的代码的另一个问题在car
内部,同样,您不应该使用字段变量bind
,而是像这样获取所需的项目:
onClick