1.滚动监听:设置回到顶部按钮的显示隐藏
binding.recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
//获取RecyclerView当前顶部显示的第一个条目对应的索引
int position = manager.findFirstVisibleItemPosition();
//根据索引来获取对应的itemView
View firstVisiableChildView = manager.findViewByPosition(position);
//获取当前显示条目的高度
int itemHeight = firstVisiableChildView.getHeight();
//获取当前Recyclerview 偏移量
int flag = (position) * itemHeight - firstVisiableChildView.getTop();
//注意事项:recyclerView不要设置padding
if(flag==0)
binding.ivTop.setVisibility(View.GONE);
else
binding.ivTop.setVisibility(View.VISIBLE);
}
});
2.设置一键回到顶部按钮的点击事件
@Override
public void goTop() {
binding.recyclerView.post(new Runnable() {
@Override
public void run() {
binding.recyclerView.scrollToPosition(0);
}
});
}
3.item的布局文件:recyclerView的item布局文件最外层一定不要设置margin
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="3dp"
app:cardElevation="0dp"
app:contentPaddingBottom="2dp"
app:contentPaddingTop="2dp">
<ImageView
imgUrl="@{product.img}"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_margin="5dp"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:transitionName="transitionImg" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="2dp"
android:text="@{product.name}"
android:textSize="14sp" />
</android.support.v7.widget.CardView>
</FrameLayout>
作者:阳光下的美好_6e13
鏈接:https://www.jianshu.com/p/e3f44b2bb26f
來源:簡書
簡書著作權歸作者所有,任何形式的轉載都請聯繫作者獲得授權並註明出處。