我正在从这个要点创建ItemDecoration
的子类:https://gist.github.com/alexfu/0f464fc3742f134ccd1e
如何让它只装饰一定条件的物品?例如,仅装饰具有特定位置的项目,ViewHolder的类型等
我已使用此代码修改了上述要点(以及对已弃用的Android API的一些更改),但所有项目仍然会进行修饰:
public boolean isDecorated(View view, RecyclerView parent) {
RecyclerView.ViewHolder holder = parent.getChildViewHolder(view);
return holder instanceof MenuIconViewHolder || holder instanceof MenuDetailViewHolder;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
if (isDecorated(view, parent)) {
if (mOrientation == VERTICAL_LIST) {
outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
} else {
outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
}
} else {
super.getItemOffsets(outRect, view, parent, state);
}
}
上述代码有什么问题? 那么,将这种代码放在ItemDecoration类中是否可以被认为是最佳实践(关注点分离)?
答案 0 :(得分:31)
你也需要在绘制方法上调用isDecorated,因为此刻你不会在这些项目上设置偏移,但你仍然会在它上面绘制。
该方法循环显示当前在屏幕上可见的RecyclerView中的所有子视图。
public void drawVertical(Canvas c, RecyclerView parent) {
final int left = parent.getPaddingLeft();
final int right = parent.getWidth() - parent.getPaddingRight();
final int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = parent.getChildAt(i);
if(isDecorated(child, parent))
{
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
.getLayoutParams();
final int top = child.getBottom() + params.bottomMargin;
final int bottom = top + mDivider.getIntrinsicHeight();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
}
public void drawHorizontal(Canvas c, RecyclerView parent) {
final int top = parent.getPaddingTop();
final int bottom = parent.getHeight() - parent.getPaddingBottom();
final int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = parent.getChildAt(i);
if(isDecorated(child, parent))
{
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
.getLayoutParams();
final int left = child.getRight() + params.rightMargin;
final int right = left + mDivider.getIntrinsicHeight();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
}