1. 程式人生 > >RecyclerView 獲取顯示item的位置

RecyclerView 獲取顯示item的位置

rvview.setOnScrollListener(new RecyclerView.OnScrollListener() {
    @Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
        super.onScrollStateChanged(recyclerView, newState);
RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
//判斷是當前layoutManager是否為LinearLayoutManager
// 只有LinearLayoutManager才有查詢第一個和最後一個可見view位置的方法 if (layoutManager instanceof LinearLayoutManager) { LinearLayoutManager linearManager = (LinearLayoutManager) layoutManager; //獲取最後一個可見view的位置 int lastItemPosition = linearManager.findLastVisibleItemPosition(); //獲取第一個可見view的位置 int firstItemPosition
= linearManager.findFirstVisibleItemPosition(); if (lastItemPosition > 10) { tvCount.setVisibility(View.VISIBLE); tvCount.setText(lastItemPosition + "\n\n" + list.size()); shouCount = true; } else { shouCount = false; tvCount.setVisibility(View.GONE); } switch
(newState) { case RecyclerView.SCROLL_STATE_IDLE: if (shouCount) { tvCount.setText("一\n" + "↑\n頂部"); } break; } LogUtils.LogE("setOnScrollListener", lastItemPosition + " " + firstItemPosition); } } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); } });