android - 如何在 ScrollView 中设置 onScrollStop 事件

标签 android android-layout

我正在开发一个新闻阅读器类型的 android 应用程序,我想在用户开始滚动新闻列表时清除我的自定义页眉和页脚栏。当用户停止滚动新闻时,这些栏应该再次出现。这样我可以为用户提供更多阅读新闻的空间。但问题是,我找不到一种方法来触发像 onScrollStop 或 onScrollStart 这样的事件。 请帮忙。

最佳答案

在我的项目中,我不得不拦截滚动的末尾,所以我实现了我自己的 ScrollListener:

public class VerticalScrollLayout extends ScrollView {
    private GestureDetector gdScrolling;
    private boolean isScrolling;

    private OnScrollListener lOnScroll;

    public VerticalScrollLayout(Context context) {
        super(context);
        setVerticalScrollBarEnabled(false);

        gdScrolling = new GestureDetector(new SimpleOnGestureListener() {
            @Override
            public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
                isScrolling = true;
                return false;
            }

            @Override
            public boolean onDown(MotionEvent e) {
                return true;
            }
        });

        setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                if (gdScrolling.onTouchEvent(event)) {
                    return false;
                }

                if(event.getAction() == MotionEvent.ACTION_UP) {
                    if(isScrolling ) {
                        isScrolling  = false;
                        if(lOnScroll != null) {
                            lOnScroll.onScrollEnded();
                        }
                    }
                }

                return false;
            }
        });
    }

    public void setOnScrollListener(OnScrollListener l) {
        lOnScroll = l;
    }

    @Override
    protected void onScrollChanged(int x, int y, int oldx, int oldy) {
        super.onScrollChanged(x, y, oldx, oldy);
        if(lOnScroll != null) {
            lOnScroll.onScrollChanged(x, y, oldx, oldy);
        }
    }

    public interface OnScrollListener {
        void onScrollChanged(int x, int y, int oldx, int oldy);
        void onScrollEnded();
    }
}

这可能不是最佳做法,但效果很好。

关于android - 如何在 ScrollView 中设置 onScrollStop 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9095946/

相关文章:

android - 如何实现可点击的ScrollView?

安卓应用问题

Android WebVIew WebViewClient

java - 在android中将布局文件转换为Java

java - 查询 Firebase 的位置范围

android - 如何/我应该使用 Mockito 对 EventBus 事件进行单元测试?

android - EditText 请求焦点

android - 在屏幕的任意位置显示 AlertDialog

android - 在具有固定宽度的 ImageView 中缩放图像

android - 在水平 ScrollView 中的 ImageView 列表之间添加边框/分隔符