Android RecyclerView paddingTop paddingBottom 无效解决方法
如果在 RecyclerView 上设置了 paddingTop 和 paddingBottom,但发现它们没有起作用,可能是因为 RecyclerView 的布局管理器(LayoutManager)使用了自己的布局规则,覆盖了 padding 属性。\n\n要解决这个问题,可以尝试以下方法:\n\n1. 在 RecyclerView 的外层包裹一层布局容器(例如 LinearLayout 或 FrameLayout),并在容器上设置 padding 属性。\n\n\n<LinearLayout\n    android:layout_width="match_parent"\n    android:layout_height="match_parent"\n    android:paddingTop="16dp"\n    android:paddingBottom="16dp">\n\n    <androidx.recyclerview.widget.RecyclerView\n        android:layout_width="match_parent"\n        android:layout_height="match_parent" />\n\n</LinearLayout>\n\n\n2. 自定义 RecyclerView 的布局管理器,并重写 calculateItemDecorationsForChild() 方法来包含 padding 的计算。\n\njava\npublic class CustomLayoutManager extends LinearLayoutManager {\n\n    public CustomLayoutManager(Context context) {\n        super(context);\n    }\n\n    @Override\n    public void calculateItemDecorationsForChild(View child, Rect outRect) {\n        super.calculateItemDecorationsForChild(child, outRect);\n        outRect.top += getPaddingTop();\n        outRect.bottom += getPaddingBottom();\n    }\n}\n\n\n然后在布局文件中使用自定义的布局管理器:\n\n\n<androidx.recyclerview.widget.RecyclerView\n    android:layout_width="match_parent"\n    android:layout_height="match_parent"\n    app:layoutManager="com.example.CustomLayoutManager" />\n\n\n这样就可以确保 paddingTop 和 paddingBottom 生效了。
原文地址: https://www.cveoy.top/t/topic/qabU 著作权归作者所有。请勿转载和采集!