I am setting up recyclerview from Firebase with the below code. This fetches the whole data every time when new child added to firebase realtime database and recyclerview scrolled to the bottom automatically. I need to stop autoscroll recyclerview when user is in the middle of the screen.
public void setUpRecyclerview() {
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
modelList.clear();
for (DataSnapshot ds:dataSnapshot.getChildren()) {
String data = (String) ds.child("data").getValue();
long time = (long) ds.child("time").getValue();
String type = (String) ds.child("type").getValue();
DealsModel model = new DealsModel(data, time, type);
modelList.add(model);
count++;
}
dealAdapter = new DealAdapter(modelList);
LinearLayoutManager layoutManager = new LinearLayoutManager(DealsActivity.this);
layoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(dealAdapter);
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
I need to perform this functionality only when a new child inserted, so that the user screen doesn’t auto scroll to bottom and a counter show on Float Button that a new message appears. Like Whatsapp/Telegram.
RecyclerView.LayoutManager linearLayoutManager = recyclerView.getLayoutManager();
int lastVisiblePosition = ( (LinearLayoutManager) linearLayoutManager ).findLastCompletelyVisibleItemPosition();
int position1 = ( (LinearLayoutManager) linearLayoutManager ).findLastVisibleItemPosition();
if(position1 != lastVisiblePosition ) {
if (positionStart >= (totalItem - 1)) {
countMsg = countMsg + 1;
Log.e("Countmsg","."+countMsg);
}
}
else {
recyclerView.scrollToPosition(totalItem - 1);
}
I need value of positionStart i.e. the value of newly instered child. How to get this.
2
Answers
If you want more granular control over the changes to the child nodes, use a
ChildEventListener
:The
onChildAdded
method here gets called initially for each child node indatabaseReference
, and subsequently once for each child node that is added. As you can see, you no need to loop overds.getChildren()
as we now get called for each child node individually.Since there are more type of changes than just additions, you’ll also want to implement
onChildChanged
,onChildRemoved
andonChildMoved
to make the corresponding update to your data structure, and then calladapter.notifyDataSetChanged()
to tell it about the change.Remove this piece of code or make it false like this.