Xamarin Android onScrollListener被多次调用

时间:2017-01-27 11:52:44

标签: android xamarin

我想在我的应用程序中创建一个无限滚动的RecyclerView。它使用Web服务并在屏幕上显示一些CardView项目。这是我到目前为止的简化代码,没有包含创建RecyclerView等。

Main.cs

protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        var categoryLayoutManager = new LinearLayoutManager(this);
        categoryList.SetLayoutManager(categoryLayoutManager);
        var onScrollListener = new OnScrollListener(categoryLayoutManager);

        onScrollListener.LoadMoreEvent += (object sender, EventArgs e) =>
        {
            Console.WriteLine("Last");
        };
    }

OnScrollListener.cs

public class OnScrollListener : RecyclerView.OnScrollListener
{
    public delegate void LoadMoreEventHandler(object sender, EventArgs e);
    public event LoadMoreEventHandler LoadMoreEvent;

    private LinearLayoutManager LayoutManager;

    public OnScrollListener(LinearLayoutManager layoutManager)
    {
        LayoutManager = layoutManager;
    }

    public override void OnScrolled(RecyclerView recyclerView, int dx, int dy)
    {
        base.OnScrolled(recyclerView, dx, dy);

        var visibleItemCount = recyclerView.ChildCount;
        var totalItemCount = recyclerView.GetAdapter().ItemCount;
        var pastVisiblesItems = LayoutManager.FindFirstVisibleItemPosition();

        if ((visibleItemCount + pastVisiblesItems) >= totalItemCount)
        {
            LoadMoreEvent(this, null);
        }
    }
}

目前,当向下滚动到最后一个项目时,我的滚动条被多次调用,因此它会带来比所需更多的项目。 我希望我的Listener被调用一次,获取项目,然后能够在新的最后一项可见时再次调用。我现有的代码是否可行?谢谢。

1 个答案:

答案 0 :(得分:2)

简单的答案是向您的侦听器添加IsLoading属性,然后仅在尚未加载某些内容时才加载。这里有一个关于你的情况可能是什么样子的想法

public class OnScrollListener : RecyclerView.OnScrollListener
{
    public delegate void LoadMoreEventHandler(object sender, EventArgs e);
    public event LoadMoreEventHandler LoadMoreEvent;
    public bool IsLoading { get; set; }
    private LinearLayoutManager LayoutManager;

    public OnScrollListener(LinearLayoutManager layoutManager)
    {
        LayoutManager = layoutManager;
    }

    public override void OnScrolled(RecyclerView recyclerView, int dx, int dy)
    {
        base.OnScrolled(recyclerView, dx, dy);

        var visibleItemCount = recyclerView.ChildCount;
        var totalItemCount = recyclerView.GetAdapter().ItemCount;
        var pastVisiblesItems = LayoutManager.FindFirstVisibleItemPosition();

        if ((visibleItemCount + pastVisiblesItems) >= totalItemCount && !IsLoading)
        {
            IsLoading = true;
            LoadMoreEvent(this, null);

            // after it's done, set it back to false
            IsLoading = false;
        }
    }
}