我上面有 RecyclerView,我有一个高度大于 255 px 的 AppBarLayout。当用户滚动 RecyclerView 时,AppBarLayout 出现 fling 问题。为了避免这种情况,我决定手动扩展 AppBarLayout。我的 RecyclerView 由 GridLayoutManager 组成,跨度为 3。我使用下面的代码来监听 RecyclerView 顶部到达
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
int firstVisiblePosition = ((LinearLayoutManager)recyclerView.getLayoutManager()).findFirstCompletelyVisibleItemPosition();
if (firstVisiblePosition == 0) {
appBarLayout.setExpanded(true, true);
}
}
}
});
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int firstVisibleItem = gridLayoutManager.findFirstCompletelyVisibleItemPosition();
if(firstVisibleItem == 0){
// your code
}
}
});
这个答案会对你有帮助。真心的你
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
totalItemCount = layoutManager.getItemCount();
visibleItemCount = layoutManager.getChildCount();
pastVisiblesItems = layoutManager.findFirstVisibleItemPosition();
if ((visibleItemCount + pastVisiblesItems) >= totalItemCount ) {
Log.d(TAG, "scroll down");
}
else{
Log.d(TAG, "scroll up");
}
}
});
我找到了一个绝妙的解决方案这里。你可以在你的内部实现它
RecyclerView.OnScrollListener
像这样:
binding.recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
if (!recyclerView.canScrollVertically(-1)) {
Log.d(TAG, "THE TOP")
} else {
Log.d(TAG, "NOT TOP")
}
}
})