gpt4 book ai didi

android - Xamarin Android onScrollListener 被调用不止一次

转载 作者:搜寻专家 更新时间:2023-11-01 09:37:38 29 4
gpt4 key购买 nike

我想在我的应用程序中创建一个无限滚动的 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);
}
}
}

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

最佳答案

简单的答案是向您的监听器添加一个 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;
}
}
}

关于android - Xamarin Android onScrollListener 被调用不止一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41893380/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com