問題描述: 當RecyclerView在佈局裏設置 android:paddingTop=“30dp” 時,滾動時頂部不能填充
官方文檔: ViewGroup setClipToPadding(boolean)方法
clipToPadding: 控件的繪製區域是否在padding裏面, 值爲true時padding那麼繪製的區域就不包括padding區域;
官方文檔:androidx/releases/recyclerview
爲什麼在這裏要單獨列出androidx/releases/recyclerview?
解答如上圖紅色圈出來的API changes的部分內容,大致意思如下:
PagerSnapHelper 和 LinearSnapHelper 現在將 RecyclerView 的內邊距考慮在內,而無論clipToPadding 的值如何
瞭解上面的知識點後,先看一下問題:
修改前的佈局代碼:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="@+id/recy"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/white"
android:paddingTop="30dp" />
</LinearLayout>
從上圖可以看到列表滾動時,頂部有30dp的白色空間,列表不能滾動到頂部
修改後的佈局代碼:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="@+id/recy"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/white"
android:clipToPadding="false"
android:paddingTop="30dp" />
</LinearLayout>
區別是: 增加一行代碼: android:clipToPadding=“false”
clipToPadding屬性默認值是true
從修改後的效果圖可以看出列表滾動時,內容是可以滾動到頂部的了。