gpt4 book ai didi

android - 避免 fragment 列表数据在 recyclerView 上重复

转载 作者:太空狗 更新时间:2023-10-29 16:12:32 24 4
gpt4 key购买 nike

我有一些 fragment 在一个 Activity 上切换。

我发现一个问题是,当我返回 fragment 时,它会显示重复的数据。

我尝试清除arrayList数据来解决。

但我想知道更聪明的方法。

有没有可能避免重复数据的这个问题?

我的 fragment 代码:

public class Vaccine extends Fragment {

private List<VaccineItem> vaccineList = new ArrayList<>();
private VaccineAdapter vaccineAdapter;
private RecyclerView recyclerVaccine;

public Vaccine() {
}

public static Vaccine newInstance() {
return new Vaccine();
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.vaccine_fragment_, container, false);

recyclerVaccine = (RecyclerView) view.findViewById(R.id.recyclerVaccine);
recyclerVaccine.setLayoutManager(new LinearLayoutManager(getActivity()));

vaccineList.clear();// i use it to slove the problem.--------------
testData();
vaccineAdapter = new VaccineAdapter(getActivity(), vaccineList);
recyclerVaccine.setAdapter(vaccineAdapter);
vaccineAdapter.notifyDataSetChanged();

return view;
}
private void testData(){
VaccineItem vaccineItem=new VaccineItem("Data1");
vaccineList.add(vaccineItem);
vaccineItem=new VaccineItem("Data2");
vaccineList.add(vaccineItem);
}
}

最佳答案

试试这个

View view; // declare this globally

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(view == null){ // initialize if view is null
view = inflater.inflate(R.layout.vaccine_fragment_, container, false);

recyclerVaccine = (RecyclerView) view.findViewById(R.id.recyclerVaccine);
recyclerVaccine.setLayoutManager(new LinearLayoutManager(getActivity()));

vaccineList.clear();// i use it to slove the problem.--------------
testData();
vaccineAdapter = new VaccineAdapter(getActivity(), vaccineList);
recyclerVaccine.setAdapter(vaccineAdapter);
vaccineAdapter.notifyDataSetChanged();
}
return view;
}

关于android - 避免 fragment 列表数据在 recyclerView 上重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41630606/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com