简体   繁体   English

当scrollView到达Android底部时如何触发事件?

[英]How to trigger an event when scrollView reach the bottom with Android?

Im looking for an event that I can use on the scrollView to be fired when the user has scrolled to the bottom.我正在寻找一个事件,当用户滚动到底部时,我可以在 scrollView 上使用该事件。

Eg my list of items should be extended with more items automatically.例如,我的项目列表应该自动扩展更多项目。

Any ideas how this can be done?任何想法如何做到这一点?

I'm thanksfull for any tip.我很感激任何提示。

Please read this article: Android: Understanding When Scrollview Has Reached The Bottom请阅读这篇文章: Android:了解 Scrollview 何时到达底部

Source code:源代码:

@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) 
{
    // Grab the last child placed in the ScrollView, we need it to determinate the bottom position.
    View view = (View) getChildAt(getChildCount()-1);

    // Calculate the scrolldiff
    int diff = (view.getBottom()-(getHeight()+getScrollY()));

    // if diff is zero, then the bottom has been reached
    if( diff == 0 )
    {
        // notify that we have reached the bottom
        Log.d(ScrollTest.LOG_TAG, "MyScrollView: Bottom has been reached" );
    }

    super.onScrollChanged(l, t, oldl, oldt);
}

If you want you can add make a custom widget.如果需要,您可以添加自定义小部件。

Example:例子:

package se.marteinn.ui;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ScrollView;


/**
 * Triggers a event when scrolling reaches bottom.
 *
 * Created by martinsandstrom on 2010-05-12.
 * Updated by martinsandstrom on 2014-07-22.
 *
 * Usage:
 *
 *  scrollView.setOnBottomReachedListener(
 *      new InteractiveScrollView.OnBottomReachedListener() {
 *          @Override
 *          public void onBottomReached() {
 *              // do something
 *          }
 *      }
 *  );
 * 
 *
 * Include in layout:
 *  
 *  <se.marteinn.ui.InteractiveScrollView
 *      android:layout_width="match_parent"
 *      android:layout_height="match_parent" />
 *  
 */
public class InteractiveScrollView extends ScrollView {
    OnBottomReachedListener mListener;

    public InteractiveScrollView(Context context, AttributeSet attrs,
            int defStyle) {
        super(context, attrs, defStyle);
    }

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

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

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        View view = (View) getChildAt(getChildCount()-1);
        int diff = (view.getBottom()-(getHeight()+getScrollY()));

        if (diff == 0 && mListener != null) {
            mListener.onBottomReached();
        }

        super.onScrollChanged(l, t, oldl, oldt);
    }


    // Getters & Setters

    public OnBottomReachedListener getOnBottomReachedListener() {
        return mListener;
    }

    public void setOnBottomReachedListener(
            OnBottomReachedListener onBottomReachedListener) {
        mListener = onBottomReachedListener;
    }


    /**
     * Event listener.
     */
    public interface OnBottomReachedListener{
        public void onBottomReached();
    }

}

I had the same problem and I solved it by using the ListView (automatically adds ScrollView if needed) and setting OnScrollListener .我遇到了同样的问题,我通过使用ListView (如果需要自动添加 ScrollView)并设置OnScrollListener来解决它。

Here is a code sample:这是一个代码示例:

        tableListView.setOnScrollListener(new OnScrollListener() {

        public void onScrollStateChanged(AbsListView view, int scrollState) {

        }

        public void onScroll(AbsListView view, int firstVisibleItem,
                int visibleItemCount, int totalItemCount) {
            if (visibleItemCount == totalItemCount)
            // too little items (ScrollView not needed)
            {
                java.lang.System.out.println("too little items to use a ScrollView!");
            }
            else {
                if ((firstVisibleItem + visibleItemCount) == totalItemCount) {
                    // put your stuff here
                    java.lang.System.out.println("end of the line reached!");
                }
            }

        }
    });

Don't try SetOnScrollChangeListener if you are working with android API below 21 (android M), you can try this :如果您使用的是低于 21 (android M) 的 android API,请不要尝试SetOnScrollChangeListener ,您可以尝试以下操作:

yourScrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
            @Override
            public void onScrollChanged() {
                int rootHeight = yourScrollView.getHeight();
                int childHeight = yourScrollView.getChildAt(0).getHeight();
                int scrollY = yourScrollView.getScrollY();
                if(childHeight - rootHeight == scrollY)
                Log.d("Hei","You Have Reach The End!");
            }
        });

It's late for this answer but if anyone stumbles upon, we can do using setOnScrollChangeListener这个答案已经晚了,但如果有人偶然发现,我们可以使用 setOnScrollChangeListener

  childScrollView.setOnScrollChangeListener(object : NestedScrollView.OnScrollChangeListener {
            override fun onScrollChange(v: NestedScrollView?, scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int) {
                when {//maxScrollPixelPoint  is defined local/global variable
                    scrollY > maxScrollPixelPoint -> {
                        maxScrollPixelPoint = scrollY
                    }
                    scrollY == maxScrollPixelPoint -> {
                        //reached bottom 
                    }
                }
            }

        })

Here is a much simpler solution without having to subclass scroll view.这是一个更简单的解决方案,无需子类滚动视图。 Assuming you have a RecyclerView recyclerView variable,假设你有一个 RecyclerView recyclerView 变量,

recyclerView.computeVerticalScrollRange() gives you the complete scroll range, or in other words, the content height. recyclerView.computeVerticalScrollRange() 为您提供完整的滚动范围,即内容高度。

(recyclerView.computeVerticalScrollOffset() gives the offset from the top as you scroll. This value will go on till the content height - scroll view height. (recyclerView.computeVerticalScrollOffset() 在你滚动时给出从顶部的偏移量。这个值将一直持续到内容高度 - 滚动视图高度。

So,所以,

    if( (recyclerView.computeVerticalScrollOffset() == 
(recyclerView.computeVerticalScrollRange() - recyclerView.getHeight()) ) {
    // You have hit rock bottom.
    }

Manipulating the scroll view's child view just seems so hacky.操作滚动视图的子视图似乎太难了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM