[英]How do I detect when a specific item reaches top of a RecyclerView in Android?
I'm creating an app with a list of questions in a RecyclerView. 我正在使用RecyclerView创建一个包含问题列表的应用程序。 In the same parent layout, I have a static TextView above the RecyclerView that displays instruction for a set of questions.
在相同的父布局中,我在RecyclerView上方有一个静态TextView,它显示一组问题的说明。 What I want is to change the text in the TextView whenever a specific question reaches the top of the RecyclerView when scrolled.
我想要的是在滚动时每当特定问题到达RecyclerView的顶部时更改TextView中的文本。 How can I accomplish this?
我怎么能做到这一点?
You would need to listen to the scrolling of your RecyclerView and get the first item displayed onto the screen. 您需要收听RecyclerView的滚动并将第一个项目显示在屏幕上。
Thanksfully, Android let us set a custom ScrollListener to a RecyclerView and with your LayoutManager you are able to know which item is shown first : 谢天谢地,Android让我们将自定义ScrollListener设置为RecyclerView,使用LayoutManager,您可以知道首先显示哪个项目:
// initialize your RecyclerView and your LayoutManager
mLinearLayoutManager = new LinearLayoutManager(getContext());
mRecyclerView.setLayoutManager(mLinearLayoutManager);
// set a custom ScrollListner to your RecyclerView
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
// Get the first visible item
int firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition();
//Now you can use this index to manipulate your TextView
}
});
EDIT : added Mateus Gondim clearance about the LayoutManager 编辑:添加关于LayoutManager的Mateus Gondim清除
You should override the default Recycler.OnScrollListener. 您应该覆盖默认的Recycler.OnScrollListener。 Have a look at this Code : https://gist.github.com/mipreamble/b6d4b3d65b0b4775a22e
看看这个代码: https : //gist.github.com/mipreamble/b6d4b3d65b0b4775a22e
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.