recycleview ItemDecora 添加内容
时间: 2023-09-04 20:16:13 浏览: 72
要向RecyclerView的Item添加装饰内容,你可以使用RecyclerView的ItemDecoration类。以下是一个示例代码,演示如何添加分割线作为装饰内容:
```
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.view.View;
import androidx.annotation.DrawableRes;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
public class DividerItemDecoration extends RecyclerView.ItemDecoration {
private Drawable divider;
public DividerItemDecoration(Context context, @DrawableRes int resId) {
divider = ContextCompat.getDrawable(context, resId);
}
@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
int left = parent.getPaddingLeft();
int right = parent.getWidth() - parent.getPaddingRight();
int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = parent.getChildAt(i);
RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
int top = child.getBottom() + params.bottomMargin;
int bottom = top + divider.getIntrinsicHeight();
divider.setBounds(left, top, right, bottom);
divider.draw(c);
}
}
}
```
你可以在你的RecyclerView中使用这个ItemDecoration类,示例如下:
```
RecyclerView recyclerView = findViewById(R.id.recyclerView);
recyclerView.addItemDecoration(new DividerItemDecoration(this, R.drawable.divider));
```
上述代码假设你已经在res/drawable文件夹中添加了一个名为"divider"的分割线资源文件。你可以根据自己的需求更改分割线的样式和颜色。
希望这能帮到你!如果你还有其他问题,请继续提问。
阅读全文