在LinearLayoutManager中設置分隔線可以通過ItemDecoration來實現。首先,你需要創建一個自定義的ItemDecoration類,并重寫它的onDraw方法來繪制分隔線。以下是一個示例代碼:
public class DividerItemDecoration extends RecyclerView.ItemDecoration {
private Drawable mDivider;
public DividerItemDecoration(Context context) {
mDivider = ContextCompat.getDrawable(context, R.drawable.divider);
}
@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
int left = parent.getPaddingLeft();
int right = parent.getWidth() - parent.getPaddingRight();
for (int i = 0; i < parent.getChildCount() - 1; i++) {
View child = parent.getChildAt(i);
RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
int top = child.getBottom() + params.bottomMargin;
int bottom = top + mDivider.getIntrinsicHeight();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
}
然后,在你的RecyclerView中設置這個ItemDecoration:
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext());
recyclerView.addItemDecoration(dividerItemDecoration);
這樣就可以在LinearLayoutManager中設置分隔線了。你也可以根據需求自定義分隔線的樣式和顏色。