我有一个方法可以检查RecyclerView中的最后一个元素是否完全可由用户看到,到目前为止我有这个代码 问题是如何检查RecyclerView是否已到达底部?
PS 我有项目分隔符
public void scroll_btn_visibility_controller(){
if(/**last item is visible to user*/){
//This is the Bottom of the RecyclerView
Scroll_Top_Btn.setVisibility(View.VISIBLE);
}
else(/**last item is not visible to user*/){
Scroll_Top_Btn.setVisibility(View.INVISIBLE);
}
}
更新 这是我尝试过的尝试之一
boolean isLastVisible() {
LinearLayoutManager layoutManager = ((LinearLayoutManager)rv.getLayoutManager());
int pos = layoutManager.findLastCompletelyVisibleItemPosition();
int numItems = disp_adapter.getItemCount();
return (pos >= numItems);
}
public void scroll_btn_visibility_controller(){
if(isLastVisible()){
Scroll_Top.setVisibility(View.VISIBLE);
}
else{
Scroll_Top.setVisibility(View.INVISIBLE);
}
}
到目前为止没有成功我认为这些内容存在问题:
int pos = layoutManager.findLastCompletelyVisibleItemPosition();
int numItems = disp_adapter.getItemCount();
答案 0 :(得分:29)
您可以在适配器中创建一个回调,每次最后一项可见时,都会向您的活动/片段发送一条消息。
例如,您可以在onBindViewHolder方法
中实现此想法@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
if(position==(getItemCount()-1)){
// here goes some code
// callback.sendMessage(Message);
}
//do the rest of your stuff
}
<强>更新强>
嗯,我知道已经有一段时间但是今天我遇到了同样的问题,我想出了一个完美的解决方案。所以,如果有人需要,我会把它留在这里:
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
LinearLayoutManager layoutManager=LinearLayoutManager.class.cast(recyclerView.getLayoutManager());
int totalItemCount = layoutManager.getItemCount();
int lastVisible = layoutManager.findLastVisibleItemPosition();
boolean endHasBeenReached = lastVisible + 5 >= totalItemCount;
if (totalItemCount > 0 && endHasBeenReached) {
//you have reached to the bottom of your recycler view
}
}
});
答案 1 :(得分:7)
假设您正在使用LinearLayoutManager
,此方法应该可以解决问题:
boolean isLastVisible() {
LinearLayoutManager layoutManager = ((LinearLayoutManager)mRecyclerView.getLayoutManager());
int pos = layoutManager.findLastCompletelyVisibleItemPosition();
int numItems = mRecyclerView.getAdapter().getItemCount();
return (pos >= numItems);
}
答案 2 :(得分:1)
尝试使用onScrollStateChanged
它将解决您的问题
答案 3 :(得分:0)
您应该使用代码进行以下更改:
boolean isLastVisible() {
LinearLayoutManager layoutManager =((LinearLayoutManager) rv.getLayoutManager());
int pos = layoutManager.findLastCompletelyVisibleItemPosition();
int numItems = disp_adapter.getItemCount();
return (pos >= numItems - 1);
}
请注意,findLastCompletelyVisibleItemPosition()返回从0开始的位置。因此,您应在numItems之后减去1。