要為ListView添加ItemDecoration,需要創建一個自定義的ItemDecoration類,并且將其應用到ListView中。
以下是一個示例代碼:
public class MyItemDecoration extends RecyclerView.ItemDecoration {
private int space;
public MyItemDecoration(int space) {
this.space = space;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
outRect.left = space;
outRect.right = space;
outRect.bottom = space;
// Add top margin for the first item to avoid double space between items
if (parent.getChildAdapterPosition(view) == 0) {
outRect.top = space;
} else {
outRect.top = 0;
}
}
}
然后在ListView中應用這個ItemDecoration:
RecyclerView recyclerView = findViewById(R.id.recyclerView);
recyclerView.addItemDecoration(new MyItemDecoration(10));
這樣就可以為ListView添加自定義的ItemDecoration,并設置間距大小。