安卓Kotlin 检测ScrollView是否到头

方法很简单,只需要

  1. 将布局文件中的ScrollView换成下面文件的LazyScrollView
<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() {}
}

即可。
代码参考:ScrollView滑动到最底端或者最顶端再加载数据

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值