0

I have a RecyclerView that is filled dynamically.

When a new message arrives, I use this code to scroll down to the last entry:

recyclerView.scrollToPosition(adapter.getItemCount() - 1);

Now the problem is: It should NOT scroll down, if the user has scrolled up to read older messages. How can I detect it?

NoobieNoob
  • 887
  • 2
  • 11
  • 31
  • Can you share a small gif/video with that behavior? – azizbekian May 04 '19 at 00:18
  • I am assuming you're doing this for a chat or messaging app? so you want when a user is scrolling up reading older messages, during which if a new message comes in, you don't want your scroll to bottom code to get executed ? – Wale May 04 '19 at 01:08
  • @Whales Exactly – NoobieNoob May 04 '19 at 08:29
  • I think noone else understood the problem – NoobieNoob May 04 '19 at 08:33
  • Here is what you can do, check if the recyclerView is already at the bottom, if yes, don't execute your scrollToPosition code, else do execute it. I will paste the sample code for you as an answer for readability. – Wale May 05 '19 at 04:10

3 Answers3

1

I,m assuming you're using a custom adapter with some kind of RecyclerView or so. Simply create static boolean variable that helps hold true when the bottom is reached in your adapter like below, i'm assuming recyclerView in this case.

public class ChatAdapter extends RecyclerView.Adapter<ChatAdapter.ViewHolder> {

    public static boolean bottomReached = false;

      @Override //Make sure it happens on bindViewHolder or related...
        public void onBindViewHolder(final ViewHolder holder, int position) {
                if (position == data.size() - 1)
                    bottomReached = true;
                else
                    bottomReached = false;

        }

}

So in your activity, for example chatActivity, we do like below.

public class ChatActivity extends AppCompatActivity{
ChatAdapter chatAdapter;

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);

        chatAdapter = new ChatAdapter(this, messagesDataSample);
}

private void gotNewMessage(){
   if(chatAdapter.bottomReached)
      recyclerView.scrollToPosition(adapter.getItemCount() - 1);
   else
      // else is not necessary as you don't want to do anything.
}

}

Hopefully this helps, else pls let me know what goes wrong.

Wale
  • 1,644
  • 15
  • 31
0

It is common problem of recyclerview. I think you will find your answer here- How to use RecyclerView.scrollToPosition() to move the position to the top of current view?

Sourav Bagchi
  • 656
  • 7
  • 13
0

To check the visible item's position you could use

yourRecyclerView.getLayoutManager().findFirstVisibleItemPosition();

You can find the reference here

For more details you could check this stackoverflow thread

Monster Brain
  • 1,950
  • 18
  • 28