Check if RecyclerView is scrollable

后端 未结 9 1741
走了就别回头了
走了就别回头了 2021-02-02 10:21

How to check if a RecyclerView is scrollable, ie, there are items below/above the visible area

I have a dropdown in my recycler view which works by using

9条回答
  •  孤街浪徒
    2021-02-02 10:53

    I had the same problem and the answers already posted, especially Fabios, brought me on the right track. The scrollRange does not support paddings though, so they need to taken into account as well if your Recyclerview has a padding.

    I'm using the following extension property in Kotlin now to determine whether or not the view is scrolling.

    /**
     * computes whether the RecyclerView's content is larger than the view container, i.e. whether or not the user can scroll
     * returns null if either layout manager or adapter is not yet set or an incompatible layout manager is used (Linear- & GridLayoutManager work)
     */
    val RecyclerView.canScroll: Boolean?
        get() {
            // if there's no adapter set, we don't know yet whether or not the view is scrollable
            if (adapter == null) return null
            val manager = layoutManager as? LinearLayoutManager ?: return null
            if (manager.orientation == RecyclerView.HORIZONTAL) {
                return computeHorizontalScrollRange() + paddingLeft + paddingRight > width
            }
            return computeVerticalScrollRange() + paddingTop + paddingBottom > height
        }
    

提交回复
热议问题