android

在Android中如何为ListView添加ItemDecoration

小樊
84
2024-08-15 10:05:36
栏目: 编程语言

要为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,并设置间距大小。

0
看了该问题的人还看了