RecyclerView position not saved after screen rotation

Viewed 128

RecyclerView position not saved after screen rotation and moves to the beginning of the list. RecyclerView находиться в Fragment, added the following code to my project, after which, in theory, the position should be saved, but this does not happen

    @Override
    public void onPause() {
        super.onPause();
        state = RLM_tasks.onSaveInstanceState();
    }

Help to figure out why the list does not save position and solve this problem Fragment completely

public class FragmentList extends Fragment {
    CardView cv_list;

    private FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();
    private CollectionReference collectionReference = firebaseFirestore.collection("Tasks");

    private AdapterTasksList adapterTasksList;
    private RecyclerView rv_tasks;
    private RecyclerView.LayoutManager RLM_tasks;

    Parcelable state;


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

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

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

    @Override
    public void onViewCreated(@NonNull final View view, @Nullable Bundle savedInstanceState)
    {

        cv_list = requireView().findViewById(R.id.cv_list);
        cv_list.setOnClickListener(v -> requireActivity().onBackPressed());

        Query query = collectionReference.orderBy("TurnTasks", Query.Direction.DESCENDING);

        FirestoreRecyclerOptions<ItemTasks> firestoreRecyclerOptions = new FirestoreRecyclerOptions.Builder<ItemTasks>()
                .setQuery(query, ItemTasks.class)
                .build();

        adapterTasksList = new AdapterTasksList((ClickTasksBlanc) getContext(), firestoreRecyclerOptions);
        adapterTasksList.startListening();
        rv_tasks = requireView().findViewById(R.id.rv_list);
        RLM_tasks = new LinearLayoutManager(getActivity());
        RLM_tasks.onRestoreInstanceState(state);
        rv_tasks.setHasFixedSize(false);
        rv_tasks.setLayoutManager(RLM_tasks);
        rv_tasks.setNestedScrollingEnabled(true);
        rv_tasks.setAdapter(adapterTasksList);
    }

    @Override
    public void onPause() {
        super.onPause();
        state = RLM_tasks.onSaveInstanceState();
    }
}

I have suspicions that the whole problem is that the list is re-created when the screen is rotated, and therefore it cannot re-revert to the previous position.

2 Answers

For these kind of situation you have to use model view- view model called mvvm you can get more detail & tutorial from official website and also see the some example of tutorial

Related