首页 > 解决方案 > 如何实现聊天屏式软键盘行为?

问题描述

我试图在示例聊天应用程序中实现特定的键盘行为,在该应用程序中,当用户打开键盘时,键盘RecyclerView会随键盘上升,但前提是最后一个聊天可见。

示例:在WhatsApp打开键盘时,当最后一条消息可见时,列表将随键盘一起上升,以便对用户保持可见。现在向上滚动一点,然后打开键盘,现在列表将保持原样,不会随着键盘上升。

标签: androidandroid-recyclerviewandroid-softkeyboard

解决方案


为了实现与键盘一起向上滚动列表的行为,我从这里得出了解决方案:https ://stackoverflow.com/a/34103263/1739882

并添加决定是否滚动列表的自定义行为,我使用以下方法获取了最后一个可见项目:

linearLayoutManager.findLastVisibleItemPosition()

并使用标志来处理场景。这是完整的代码:

//Setup editText behavior for opening soft keyboard
    activityChatHeadBinding.edtMsg.setOnTouchListener((v, event) -> {
        InputMethodManager keyboard = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (keyboard != null) {
            LinearLayoutManager linearLayoutManager = (LinearLayoutManager) activityChatHeadBinding.recyclerView.getLayoutManager();
            isScrollToLastRequired = linearLayoutManager.findLastVisibleItemPosition() == chatNewAdapter.getItemCount() - 1;
            keyboard.showSoftInput(findViewById(R.id.layout_send_msg), InputMethodManager.SHOW_FORCED);
        }
        return false;
    });

//Executes recycler view scroll if required.
activityChatHeadBinding.recyclerView.addOnLayoutChangeListener((v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) -> {
            if (bottom < oldBottom && isScrollToLastRequired) {
                activityChatHeadBinding.recyclerView.postDelayed(() -> activityChatHeadBinding.recyclerView.scrollToPosition(
                        activityChatHeadBinding.recyclerView.getAdapter().getItemCount() - 1), 100);
            }
        });

推荐阅读