在 Android ListView 或 RecyclerView 中圆角
时间: 2023-08-29 17:04:29 浏览: 136
你可以使用自定义的 ItemDecoration 来实现在 Android ListView 或 RecyclerView 中圆角。
下面是一个示例代码,演示如何在 RecyclerView 中应用圆角:
```java
public class RoundedCornerItemDecoration extends RecyclerView.ItemDecoration {
private final int radius;
public RoundedCornerItemDecoration(int radius) {
this.radius = radius;
}
@Override
public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
super.getItemOffsets(outRect, view, parent, state);
outRect.left = radius;
outRect.right = radius;
outRect.top = radius;
outRect.bottom = radius;
}
@Override
public void onDraw(@NonNull Canvas canvas, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
super.onDraw(canvas, parent, state);
Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setAntiAlias(true);
for (int i = 0; i < parent.getChildCount(); i++) {
View child = parent.getChildAt(i);
canvas.drawRoundRect(new RectF(child.getLeft(), child.getTop(), child.getRight(), child.getBottom()), radius, radius, paint);
}
}
}
```
在 RecyclerView 中应用这个 ItemDecoration:
```java
recyclerView.addItemDecoration(new RoundedCornerItemDecoration(16));
```
这个示例代码中,我们使用了一个自定义的 ItemDecoration,将 RecyclerView 的每个 item 都应用了圆角。你可以根据需要调整圆角的半径。
阅读全文