如何获取回收者视图的项目的x / y。 mRecyclerView.getChildAt(1)使子项在位置1处可见。 我希望将列表子项置于第一位置,以便在达到0,0时执行某些操作。
if(mRecyclerView.getChildAt(1).getTop() == 0){
//do some operation
}
我怎么能实现它?
答案 0 :(得分:1)
有两种方法可以实现它:
创建您自己的LayoutManager
(例如,会扩展LinearLayoutManager
),将其附加到您的RecyclerView
并在滚动时获得RecyclerView
第一个子位置。< / p>
public class MyLinearLayoutManager extends LinearLayoutManager {
//Constructor stuff
@Override
public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
if (getChildAt(1).getTop() == 0) {
// do stuff...
}
return super.scrollVerticallyBy(dy, recycler, state);
}
@Override
public void onLayoutCompleted(RecyclerView.State state) {
super.onLayoutCompleted(state);
// check your stuff here too. It'll be called when new views appeared
}
}
将滚动侦听器附加到RecyclerView
并获取其中的视图位置。
RecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
RecyclerView.ViewHolder holder = RecyclerView.findViewHolderForAdapterPosition(1);
View view = holder.itemView;
if (view.getTop() == 0){
//...
}
}
});