1

I have a RecyclerView, data is loaded into it in real time, how do I make saveInstanceState? That is, so that when you rotate the screen, it does not go to the beginning of the list, but remains in the same position?

Fragment is where the RecyclerView

public class FragmentPraList extends Fragment {
    CardView cv_pra_list;

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

    AdapterTasksPraList adapterTasksPraList;
    RecyclerView rv_tasks_pra;
    RecyclerView.LayoutManager RLM_tasks_pra;
    static ArrayList<ItemTasks> itemTasks;

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

    @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
        View view;
        view = inflater.inflate(R.layout.fragment_pra_list, container, false);
        return view;
    }

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

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

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

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

        adapterTasksPraList = new AdapterTasksPraList(itemTasks, (ClickTasksBlanc) getContext(), firestoreRecyclerOptions);
        rv_tasks_pra = requireView().findViewById(R.id.rv_pra_list);
        RLM_tasks_pra = new LinearLayoutManager(getActivity());
        rv_tasks_pra.setHasFixedSize(false);
        rv_tasks_pra.setLayoutManager(RLM_tasks_pra);
        rv_tasks_pra.setNestedScrollingEnabled(true);
        rv_tasks_pra.setAdapter(adapterTasksPraList);
    }
    @Override
    public void onStart() {
        super.onStart();
        adapterTasksPraList.startListening();
    }
}
  • Just don't set the adapter over and over again. – Martin Zeitler Apr 06 '21 at 07:30
  • @MartinZeitler I didn't understand your answer, would you describe it? –  Apr 06 '21 at 07:36
  • Did you try using `layoutManager.onSaveInstanceState()` method in conjunction with `layoutManager.onRestoreInstanceState(state)`? [This answer](https://stackoverflow.com/a/43905725/5647037) may help you out. Also, on that question I linked, there's a few other ways to do it (manually save the position of the first visible item, for instance). – Vucko Apr 06 '21 at 08:33

0 Answers0