gpt4 book ai didi

android - 如何仅为特定的 ViewType 设置 ItemDecoration?

转载 作者:行者123 更新时间:2023-11-29 18:29:05 27 4
gpt4 key购买 nike

我想为 Header Type 绘制一个默认的 ItemDecorationRecycleView 中。但是 divider 是为每个 ViewType 显示的。

自定义装饰:

class DividerDecoration(context: Context, orientation: Int)
: DividerItemDecoration(context, orientation){

override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
val position = parent.getChildAdapterPosition(view)
val viewType = parent.adapter!!.getItemViewType(position)
if (viewType == ITEM_VIEW_TYPE_HEADER){
super.getItemOffsets(outRect, view, parent, state)
} else {
outRect.setEmpty()
}
}
}

设置:

val itemDecoration = DividerDecoration(binding.recyclerView.context, 
DividerItemDecoration.VERTICAL)
binding.recyclerView.addItemDecoration(itemDecoration)

对于为什么会发生这种情况有什么建议吗?

更新

上面的代码是有效的。但是有一个错误。启动应用程序后,分隔符出现在所有元素中,然后仅出现在正确的元素中。为什么会这样?

enter image description here

最佳答案

下面介绍了如何根据 View 类型或位置显示或隐藏分隔线。将其包含在您的 Activity/fragment 中。

recyclerView.addItemDecoration(new DividerItemDecoration(this, linearLayoutManager.getOrientation()) {
@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
Drawable d = getDrawable();
for (int i = 0; i < parent.getChildCount(); i++) {
View view = parent.getChildAt(i);
int position = parent.getChildAdapterPosition(view);
int viewType = parent.getAdapter().getItemViewType(position);

// Draw divider only for view type 2 (can also put position here to remove for certain positions)
if(viewType == 2) {
RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) view.getLayoutParams();
int top = view.getBottom() + params.bottomMargin;
int bottom = top + d.getIntrinsicHeight();
d.setBounds(0, top, parent.getRight(), bottom);
d.draw(c);
}
}
}
});

关于android - 如何仅为特定的 ViewType 设置 ItemDecoration?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57377913/

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