显示/隐藏键盘时,RecyclerView保持滚动位置

时间:2019-02-07 01:12:01

标签: scroll android-recyclerview android-softkeyboard

我想要实现的是显示或隐藏键盘时保持垂直偏移。屏幕的行为应类似于whatsapp或不和谐的聊天屏幕。每当您打开键盘时,都会保持垂直滚动(不是项目位置,而是实际滚动)。

我尝试做的是:

 recycler_view.addOnScrollListener(object : RecyclerView.OnScrollListener() {
        var state = AtomicInteger(RecyclerView.SCROLL_STATE_IDLE)

        override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
            state.compareAndSet(RecyclerView.SCROLL_STATE_IDLE, newState)
            when (newState) {
                RecyclerView.SCROLL_STATE_IDLE -> {
                    if (!state.compareAndSet(RecyclerView.SCROLL_STATE_SETTLING, newState)) {
                        state.compareAndSet(RecyclerView.SCROLL_STATE_DRAGGING, newState)
                    }
                }
                RecyclerView.SCROLL_STATE_DRAGGING -> {
                    state.compareAndSet(RecyclerView.SCROLL_STATE_IDLE, newState)
                }
                RecyclerView.SCROLL_STATE_SETTLING -> {
                    state.compareAndSet(RecyclerView.SCROLL_STATE_DRAGGING, newState)
                }
            }
        }

        override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
            if (state.get() != RecyclerView.SCROLL_STATE_IDLE) {
                verticalScrollOffset.set((recycler_view).computeVerticalScrollOffset())
            }
        }

然后:

recycler_view.addOnLayoutChangeListener { _, _, _, _, bottom, _, _, _, oldBottom ->
        if (oldBottom != bottom) {
            recycler_view.post {

                recycler_view.scrollTo(verticalScrollOffset.get())
            }
        }
    }

但是会引发异常:

RecyclerView does not support scrolling to an absolute position. Use scrollToPosition instead

我还尝试了使用layoutmanager的scrollToPositionWithOffset(0,verticalScrollOffset.get()),但这也没有用。

一定有一种我所缺少的简单方法。 只要在显示/隐藏键盘时显示的最后一个/第一个项目都相同,我就可以不使用完全相同的偏移量。

0 个答案:

没有答案