簡體   English   中英

如何在更改片段上保存片段回收視圖數據?

[英]How to save Fragment recyclerview data on change fragment?

我一直在嘗試使用 onStateInstance 但總是返回 null 並且我不知道如何使用 ViewModel。

我從 db 獲取數據到 recyclerview,我不想在導航到另一個片段時再次下載數據。 (我將使用 swipeRefreshLayout 更新數據)。

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v =inflater.inflate(R.layout.fragment_search, container, false);

    
           initComponents(v);
           initRecyclerViewDB(v);


    return v;
}

如果我的列表不是 null,我需要保存我的列表並且不要調用方法 initRecyclerView。

public void initRecyclerViewDB(View v){
    db.collection("post").orderBy("postBy", Query.Direction.ASCENDING).whereNotEqualTo("postBy",mAuth.getCurrentUser().getUid())
            .get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
        @Override
        public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
            postList.clear();
            for (DocumentSnapshot ds:queryDocumentSnapshots.getDocuments()) {
                postList.add(ds.toObject(Post.class));
            }
            postAdapter.notifyDataSetChanged();
        }
    });

在簡歷中,我想保存一個 arraylist 以放入我的 recyclerview。

答案是使用視圖 model:

public class YourViewModel extends ViewModel {
private final MutableLiveData<ArrayList<Post>> selectedItem = new MutableLiveData<>();

public void setData(ArrayList<YourList> item){
    selectedItem.setValue(item);
}

public LiveData<ArrayList<YourList>> getSelectedItem(){

    return selectedItem;
 }                                                                          
}

在創建視圖時:

 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v =inflater.inflate(R.layout.fragment_search, container, false);

    viewModel = new ViewModelProvider(requireActivity()).get(PostViewModel.class);
    viewModel.getSelectedItem().observe(getViewLifecycleOwner(), new Observer<ArrayList<Post>>() {
        @Override
        public void onChanged(ArrayList<Post> posts) {
            postList.clear();
            postList.addAll(posts);
            postAdapter.notifyDataSetChanged();
        }
    });


    if (postList.isEmpty()){
        initRecyclerViewDB(v);
    }else {
        Toast.makeText(getContext(), "Save", Toast.LENGTH_SHORT).show();
    }

    initComponents(v);



    return v;
}

如果列表為空將從數據庫導入數據,否則將使用 viewModel。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM