您可以擴展RecyclerView.ItemDecoration
並覆蓋onDraw
和getItemOffsets
。
使用DividerItemDecoration
作爲參考,並將裸露的基本要素複製到您自己的類中。
如果你這樣做,你會像這樣結束:
public class SimpleDividerDecoration extends RecyclerView.ItemDecoration {
private Drawable divider;
private final Rect bounds = new Rect();
public SimpleDividerDecoration(Drawable divider) {
this.divider = divider;
}
@Override
public void onDraw(Canvas canvas, RecyclerView parent, RecyclerView.State state) {
final int left = 0;
final int right = parent.getWidth();
final int childCount = parent.getChildCount() - 1;
for (int i = 0; i < childCount; i++) {
final View child = parent.getChildAt(i);
parent.getDecoratedBoundsWithMargins(child, bounds);
final int bottom = bounds.bottom + Math.round(child.getTranslationY());
final int top = bottom - divider.getIntrinsicHeight();
divider.setBounds(left, top, right, bottom);
divider.draw(canvas);
}
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
final int position = parent.getChildAdapterPosition(view);
final int lastPosition = parent.getAdapter().getItemCount() - 1;
if (position < lastPosition) {
outRect.set(0, 0, 0, divider.getIntrinsicHeight());
}
}
}
如果你比較這與DividerItemDecoration
,你會發現,它消除了橫向佈局的支持。另外,您可以直接將drawable
傳遞給構造函數。
的- 1
你看到這兩種方法是負責清除最後一個除法:
- 它可以防止
onDraw
從圖紙的最後一個分頻器。
- 它防止
getItemOffsets
提供空間(像素)爲最後一個分割器佔用。
實驗
- 從
getItemOffsets
刪除- 1
,但它留在onDraw
。
- 打開 手機的開發人員選項中的「顯示佈局邊界」。
- 設置你的分隔器高度的東西較大,如
20dp
如果你現在運行你的項目,你會發現,雖然最後分頻器不繪製,空間仍然提供了它。
請勿使用默認分隔線。您可以在回收站視圖xml項目中添加分隔線,並根據需要顯示或隱藏基礎。 – james
發佈您的分頻器項目裝飾器代碼。 –