根据ItemViewType过滤RecyclerView

问题描述 投票:0回答:1

我获取了一份优惠列表(OfferBaseModel)。

Offers
可以有两种类型 个人最爱 。现在我想在选项卡选择上显示这些

open class OfferBaseModel -> Parent Class
data class PersonalOfferModel(val personalOffer: PersonalOffer) : OfferBaseModel()
data class FavoriteOfferModel(val product: Product) : OfferBaseModel() 

我必须对这两个项目使用相同的

RecyclerView
。如果我点击 PersonOffer Tab
RecyclerView
应仅过滤 PersonalOfferItemViewType,当我单击 FavouriteOffer Tab 时,它应仅显示 FavouriteItemViewType。当我点击第三个 tab(All) 时。它应该显示两种类型的数据

我必须过滤相同的列表,因为我必须跟踪在任何选项卡中查看过一次的报价。

我不想在选项卡选择上提供新列表。仅根据 viewItemType 进行过滤。

所有优惠选项卡 || 最喜欢的优惠选项卡 || 个人优惠选项卡

但是它下面的 RecyclerView 与提供给它的

same list
保持不变。仅过滤上述选项卡上的选择。

override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
    when (getItemViewType(position)) {
        TYPE_PERSONAL_SECTION -> (holder as PersonalOfferViewHolder).bind(position)
        TYPE_FAVOURITE_SECTION -> (holder as FavouriteOfferViewHolder).bind(position)
    }
}

override fun getItemViewType(position: Int): Int {
    return if (sections[position].shopSectionEntity.styling == "SecondarySection") {
        TYPE_PERSONAL_SECTION
    } else {
        TYPE_FAVOURITE_SECTION
    }
}

因为我创建了一个

TrackableRecyclerView
。每个项目必须是
tracked once
。我的意思是,如果在
个人优惠选项卡
中查看Personal Offer。如果相同的产品显示在
所有部分选项卡
中,则analytics tracking

不应该再次调用
android kotlin android-recyclerview tracking
1个回答
0
投票

从现有代码中进行推断是非常困难的,但我想提供一些逻辑。

enum class ViewType {
    PERSONAL, FAVOURITE, BOTH
} // your condition view

var currentViewType = ViewType.BOTH // default view

fun updateViewType(viewType: ViewType) {
    currentViewType = viewType
    notifyDataSetChanged() // or diffUtil
}

override fun getItemViewType(position: Int): Int {
    return when (currentViewType) {
        ViewType.PERSONAL -> if (sections[position] is PersonalOfferModel) {
            TYPE_PERSONAL_SECTION
        } else -1
        ViewType.FAVOURITE -> if (sections[position] is FavoriteOfferModel) {
            TYPE_FAVOURITE_SECTION
        } else -1
        else -> if (sections[position] is PersonalOfferModel) {
            TYPE_PERSONAL_SECTION
        } else if (sections[position] is FavoriteOfferModel) {
            TYPE_FAVOURITE_SECTION
        } else -1
    }
}

和你的条件按钮

firstButton.setOnClickListener {
    adapter.updateViewType(ViewType.PERSONAL)
}

secondButton.setOnClickListener {
    adapter.updateViewType(ViewType.FAVOURITE)
}

thirdButton.setOnClickListener {
    adapter.updateViewType(ViewType.BOTH)
}
© www.soinside.com 2019 - 2024. All rights reserved.