以下是一个继承自 NestedScrollView 的示例代码,用于返回 NestedScrollView 是否正在滚动:

import android.content.Context;
import android.util.AttributeSet;
import androidx.core.widget.NestedScrollView;

public class MyNestedScrollView extends NestedScrollView {

    private boolean isScrolling = false;

    public MyNestedScrollView(Context context) {
        super(context);
    }

    public MyNestedScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyNestedScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
        isScrolling = true;
    }

    @Override
    public void onScrollStateChanged(int state) {
        super.onScrollStateChanged(state);
        if (state == SCROLL_STATE_IDLE) {
            isScrolling = false;
        }
    }

    public boolean isScrolling() {
        return isScrolling;
    }
}

在这个示例中,我们创建了一个名为 MyNestedScrollView 的自定义 NestedScrollView 类。它包含一个名为 isScrolling 的私有变量,用于表示 NestedScrollView 是否正在滚动。

我们重写了 onScrollChanged() 方法和 onScrollStateChanged() 方法,以在滚动状态发生变化时更新 isScrolling 变量。在 onScrollChanged() 中,我们将 isScrolling 设置为 true,表示 NestedScrollView 正在滚动。在 onScrollStateChanged() 中,当滚动状态变为 SCROLL_STATE_IDLE(即滚动停止时),我们将 isScrolling 设置为 false。

最后,我们添加了一个公共的 isScrolling() 方法,用于返回 isScrolling 变量的值。这样,我们就可以通过调用 isScrolling() 方法来获取 NestedScrollView 是否正在滚动的状态。

Android 自定义 NestedScrollView 判断滚动状态示例代码

原文地址: https://www.cveoy.top/t/topic/o0Mb 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录