键盘打开时相应向上滚动 RecyclerView

Scroll RecyclerView up accordingly when keyboard opens(键盘打开时相应向上滚动 RecyclerView)

本文介绍了键盘打开时相应向上滚动 RecyclerView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个聊天活动,就像 facebook messenger,底部有一个 EditText,上面是消息的 RecyclerView.当键盘打开时,我想向上滚动 RecyclerView 到底应该向上滚动多少.更具体地说,假设 RecyclerView 中有 5 条消息,当前第三条消息就在 EditText 的上方.因此,当键盘打开时,我想像以前一样将第三条消息保留在 EditText 上方.我已经搜索但找不到.如果这是一个重复的问题,如果有人可以提供链接,我将不胜感激.

I have created a chat activity and like facebook messenger, there is an EditText at the bottom and above is the RecyclerView of messages. When Keyboard opens, I want to scroll RecyclerView up exactly how much it should scroll up. To be more specific, lets assume there are 5 messages in the RecyclerView and currently 3rd message is just above the EditText. So when keyboard is open, I want to keep 3rd message just above the EditText like before. I have searched but could not find. If this is a duplicate question, I will be grateful if anyone can provide the link.

推荐答案

recyclerView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
        @Override
        public void onLayoutChange(View view, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
            if ( bottom < oldBottom) {
                recyclerView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        recyclerView.scrollToPosition(adapter.getItemCount());
                    }
                }, 100);
            }
        }
    });

如果它不起作用使用 smoothScrollToPosition 而不是 scrollToPosition

if it not work Use smoothScrollToPosition instead of scrollToPosition

这对我有用.

这篇关于键盘打开时相应向上滚动 RecyclerView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:键盘打开时相应向上滚动 RecyclerView

基础教程推荐