您的当前位置:首页正文

安卓Kotlin 检测ScrollView是否到头

2024-12-01 来源:个人技术集锦

方法很简单,只需要

<xxx.xxx.xxx.LazyScrollView
    android:id="@+id/s"
    android:xxxx
    .... ....>

    <LinearLayout
        android:id="@+id/l"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" />
</xxx.xxx.xxx.LazyScrollView>
//LazyScrollView.kt
//fumiama 20200730
package xxx.xxx.xxx

import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.widget.ScrollView

class LazyScrollView : ScrollView {
    private val view: View?
        get() = getChildAt(0)

    constructor(context: Context?) : super(context)
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context?, attrs: AttributeSet?, defStyle: Int) : super(context, attrs, defStyle)

    init {
        setOnTouchListener { _, event ->
            when (event.action) {
                MotionEvent.ACTION_UP -> this.postDelayed({
                    if (view != null && onScrollListener != null) {
                        if (onScrollListener != null) {
                            //Log.d("MyS", "view?.measuredHeight: ${view?.measuredHeight}, scrollY: $scrollY, height: $height")
                            when {
                                view?.measuredHeight?:0 <= scrollY + height -> onScrollListener?.onBottom()
                                scrollY == 0 -> onScrollListener?.onTop()
                                else -> onScrollListener?.onScroll()
                            }
                        }
                    }
                }, 233)
            }
            false
        }
    }
    /**
     * 定义接口
     * @author admin
     */
    interface OnScrollListener {
        fun onBottom()
        fun onTop()
        fun onScroll()
    }
    var onScrollListener: OnScrollListener? = null
}
  1. 在想要监听的地方override接口
s.onScrollListener = object :LazyScrollView.OnScrollListener{
    override fun onTop() {}
    override fun onBottom() {}
    override fun onScroll() {}
}

即可。
代码参考:

显示全文