英文:
RecyclerView.addOnScrollListener() not getting called when scrolling down
问题
我的应用程序使用RecyclerView来加载和显示列表中的项目,每次显示20个。我添加了一个滚动监听器,如下所示:
recentItemArrayAdapter = new RecentCommentsAdapter(this, activity, itemList);
recent_comments_view = findViewById(R.id.recent_comments_view);
recent_comments_view.setAdapter(recentItemArrayAdapter);
recent_comments_view.addItemDecoration(new DividerItemDecoration(activity,
DividerItemDecoration.VERTICAL));
recent_comments_view.setLayoutManager(new LinearLayoutManager(this));
// 将滚动监听器添加到RecyclerView
recent_comments_view.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
if (layoutManager != null &&
layoutManager.findLastCompletelyVisibleItemPosition() ==
itemList.size() - 1) {
// 到达列表末尾,加载更多数据
fetchNextBatch(documents.get(documents.size() -1));
}
}
});
当我向下滚动时,我希望监听器被调用,但事实并非如此。值得一提的是,我使用的是Linux笔记本上的Android Studio Flamingo版本2022.2.1 Patch 1。
英文:
My app uses a RecyclerView to load and display items in a list, 20 at a time. I attached a scroll listener like so:
recentItemArrayAdapter = new RecentCommentsAdapter(this, activity, itemList);
recent_comments_view = findViewById(R.id.recent_comments_view);
recent_comments_view.setAdapter(recentItemArrayAdapter);
recent_comments_view.addItemDecoration(new DividerItemDecoration(activity,
DividerItemDecoration.VERTICAL));
recent_comments_view.setLayoutManager(new LinearLayoutManager(this));
// Add the scroll listener to RecyclerView
recent_comments_view.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
if (layoutManager != null &&
layoutManager.findLastCompletelyVisibleItemPosition() ==
itemList.size() - 1) {
// End of the list is reached, load more data
fetchNextBatch(documents.get(documents.size() -1));
}
}
});
When I scroll down, I expect the listener to be called, but it doesn't. FWIW, I'm using Android Studio Flamingo version 2022.2.1 Patch 1 on a Linux laptop.
答案1
得分: 0
我有两个onScrollListeners的代码:一个在活动的onCreate()中,另一个在对话框窗口中。活动中的那个被调用了,但只有当我意外尝试滚动主页时才注意到它。我移除了onCreate()中的onScrollListener(),对话框窗口中的监听器正如预期地被调用。
英文:
It turned out I had code TWO onScrollListeners: one in onCreate() in the activity and the other in a dialog window. The one in the activity was getting called, but I only noticed it when I accidentally tried to scroll the main page. I removed the onScrollListener() in onCreate() and the listener in the dialog window is getting called, as expected.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论