Slyce-Inc / SlyceMessaging

A messaging library for Android
MIT License
968 stars 173 forks source link

Recycler view does not scroll to last item when keyboard is opened #41

Open chitrey opened 7 years ago

chitrey commented 7 years ago

I think this is RecyclerView issue. Could you please tell me how to fix it or fix it in the upcoming update. Many thanks

camclendenin commented 7 years ago

@chitrey I solved this by adding the following in my activity which contains the slyce messaging fragment. It's a bit ugly IMO but it works.

At the end of onCreate() I added...

        final View contentView = getRecyclerView();
        contentView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {

                Rect r = new Rect();
                contentView.getWindowVisibleDisplayFrame(r);
                int screenHeight = contentView.getRootView().getHeight();

                // r.bottom is the position above soft keypad or device button.
                // if keypad is shown, the r.bottom is smaller than that before.
                int keypadHeight = screenHeight - r.bottom;

                if (keypadHeight > screenHeight * 0.15) { // 0.15 ratio is perhaps enough to determine keypad height.
                    // keyboard is opened
                    if (!scrollingToBottom) {
                        scrollingToBottom = true;
                        scrollRecyclerViewToBottom(getRecyclerView());
                    }
                }
                else {
                    // keyboard is closed
                    scrollingToBottom = false;
                }
            }
        });
    private static void scrollRecyclerViewToBottom(RecyclerView recyclerView) {
        RecyclerView.Adapter adapter = recyclerView.getAdapter();
        if (adapter != null && adapter.getItemCount() > 0) {
            recyclerView.scrollToPosition(adapter.getItemCount() - 1);
        }
    }
RodrigoBertotti commented 6 years ago

Thank you @camclendenin

moraruuvasile commented 4 years ago
    message_recycler.apply {
        val layout = LinearLayoutManager(context)
        layout.stackFromEnd = true
        layoutManager = layout
        adapter = chatsAdapter
    }

in another listener where change my data chatsAdapter.notifyDataSetChanged() message_recycler.scrollToPosition(listMessage.size-1)