在Android中如何为ListView添加ItemDecoration

avatar
作者
筋斗云
阅读量:0

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

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!