Always Learner
Always Learner

Reputation: 3016

How to set scroll position when using RecyclerView with FirestoreRecyclerAdapter?

I'm using a RecyclerView to display some data from a Firestore database. I'm using as an adapter, the FirestoreRecyclerAdapter for obvious reasons. I'm successfully displaying all 35 items in my RecyclerView. The problem is, I cannot scroll to a specific position. This is what I have tried:

recyclerView = locationsFragmentView.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(context));

FirestoreRecyclerOptions<MyModelClass> options = new FirestoreRecyclerOptions.Builder<MyModelClass>().setQuery(query, MyModelClass.class).build();
adapter = new MyFirestoreRecyclerAdapter(options);
recyclerView.setAdapter(adapter);
recyclerView.setHasFixedSize(false);
recyclerView.getLayoutManager().scrollToPosition(10);

Everytime I open my app, I'm always positioned at the first position and not on the 10'th as I specified in the scrollToPosition() method.

I have also used:

recyclerView.scrollToPosition(10);

and

recyclerView.smoothScrollToPosition(10);

But without luck. How do I scroll to specific position? Thanks!

Upvotes: 3

Views: 848

Answers (4)

waqas Ahmad
waqas Ahmad

Reputation: 1

I solved my problem with a Simpler solution.

I just called adapter.startListening(); in onViewCreated() instead of onStart() and called adapter.stopListening(); in onDestroyView() instead of onStop() That prevented the entire list from regenerating while coming back from the next activity and thus retained the scroll position where it was previously.

Source: https://github.com/firebase/FirebaseUI-Android/issues/998#issuecomment-342413662

Upvotes: 0

pz64_
pz64_

Reputation: 2252

In my case, I didn't want move to a specific position, instead I just wanted to keep the original position after returning from a different Activity or returning from background.

I just added this empty listener and it's working.

 listAdapter.snapshots.addChangeEventListener(object : ChangeEventListener {
        override fun onChildChanged(
            type: ChangeEventType,
            snapshot: DocumentSnapshot,
            newIndex: Int,
            oldIndex: Int
        ) {
        }

        override fun onDataChanged() {
        }

        override fun onError(e: FirebaseFirestoreException) {
        }
    })

Here listAdapter is FirestoreRecyclerAdapter.

Note: There must have some negative consequences on doing this.

Upvotes: 0

LS_
LS_

Reputation: 7139

The recyclerView doesn't scroll because it's still empty when you call recyclerView.scrollToPosition(10);, you should move that code after the recyclerView gets populated from the Firebase response, probably inside a callback.

Upvotes: 2

Kamlesh
Kamlesh

Reputation: 447

Instead of using recyclerView.scrollToPosition(10); try to use below code to set position in recyclerview

recyclerView.smoothScrollToPosition(10);

Upvotes: 1

Related Questions