gpt4 book ai didi

android - 如何选择性地装饰 RecyclerView 项目

转载 作者:IT老高 更新时间:2023-10-28 21:38:17 26 4
gpt4 key购买 nike

我正在根据这个要点创建 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 类中是否被认为是最佳实践(关于关注点分离)?

最佳答案

您还需要在 draw 方法上调用 isDecorated,因为此时您没有在这些项目上放置偏移量,但您仍然在上面绘制。

该方法循环遍历当前在屏幕上可见的 RecyclerView 中的所有 subview 。

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);
}
}
}

关于android - 如何选择性地装饰 RecyclerView 项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28232909/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com