Search code examples
androidandroid-recyclerviewscrollkeyboard

Scroll down when adding item to RecyclerView while keyboard is open


When I add a new list item, with the keyboard still open, the list item appears behind the keyboard and is thus invisible. How do I scroll it automatically down to it becomes visible?

Keep in mind that I have already solved the following:

  • When opening keyboard scroll the RecyclerView to make the last item visible: Solved

The last remaining issue is when the keyboard is already open. It works fine when I open the keyboard for the first time. It's when I hit "send" that the item is added behind the keyboard and when I want it to scroll up

  1. I hit "send message" New message

  2. This is what happens. It's hidden behind the keyboard

When I've hit "send message" button


Solution

  • Set your LayoutManager to reverse layout to have the RecyclerView retain its positioning against its bottom edge instead of the top one:

    LinearLayoutManager layoutManager = new LinearLayoutManager(this);
    layoutManager.setReverseLayout(true);
    myRecycler.setLayoutManager(layoutManager);
    

    There should be no need to automatically scroll to the last position of your Adapter anymore so, if you previously had code to do so, you should remove it.

    You will also have to reverse the order of the data set in your Adapter to match the ordering you originally had (If your data was originally sorted Ascending, then you should change it to Descending). For your case, you would want to sort by Descending time to have the items arranged by most recent at the bottom and oldest at the top of the RecyclerView.

    And, if you're directly adding to the Adapter's data set, you should add to the beginning of the Adapter's list:

    myDataList.add(0, myNewItem); // Add to the beginning of the list shifting previous items over
    notifyDataSetChanged(); // Notify the adapter to refresh