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