背景:RecyclerView 左右滑动时,需要获取当前显示在页面上的选项卡
步骤:
1. RecyclerView 添加addOnScrollListener,回调中可以直接获取对应Item Index
xxxRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); if (newState == RecyclerView.SCROLL_STATE_IDLE) { // 当 RecyclerView 的滑动事件完成(滑动停止)时,会回调到这里 LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager(); // 获取当前页面内第一个完整显示的Item,由于我的子Item自动占满页面宽度,所以当前页面内完整显示的第一个Item,就是我所需要的Item int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition(); int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition(); int firstCompletelyVisibleItemPosition = layoutManager.findFirstCompletelyVisibleItemPosition(); int lastCompletelyVisibleItemPosition = layoutManager.findLastCompletelyVisibleItemPosition(); // 判断获取的position不为-1,则为有效数据 if (firstCompletelyVisibleItemPosition != -1) { currentIndex = firstCompletelyVisibleItemPosition; // 显示当前选项卡的位置(对于用户来讲,当前选项卡的位置为position+1) String currentLocation = (firstCompletelyVisibleItemPosition + 1) + ""; if (tvCurrent != null) { tvCurrent.setText(currentLocation); } // 获取当前选项卡的viewHolder实例,可以自行做业务逻辑处理 RecyclerView.ViewHolder viewHolder = xxxRecyclerView.findViewHolderForAdapterPosition(firstCompletelyVisibleItemPosition); if (viewHolder != null) { View itemView = viewHolder.itemView; EditText editText = (EditText)itemView.findViewById(R.id.et_xxx); editText.requestFocus(); } } } } @Override public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); // 这个方法会在 RecyclerView 滚动时持续回调,你也可以在这里获取和处理你关心的 item 的位置 } });
标签:int,recyclerView,Item,Android,RecyclerView,layoutManager,firstCompletelyVisibleI From: https://www.cnblogs.com/uoky/p/18236526