使用 getItemViewType 具有多个项目的适配器

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

我有一个由组标题分隔的联系人列表。所以我在我的适配器中使用了 getItemViewType :

    @Override
    public int getItemViewType(int position) {
        ContactItem contactItem = mContacts.get(position);
        if (contactItem.getContactSeparator() == null) {
            if (contactItem.getContact().getContactType() == ContactType.SINGLE) {
                if (mShowSeparator) {
                    return TYPE_CONTACT;
                }
                return TYPE_SEARCH_CONTACT;
            }
            if (mShowSeparator) {
                return TYPE_CONTACT_MULTIPLE;
            }
            return TYPE_SEARCH_CONTACT_MULTIPLE;
        }
        return TYPE_SEPARATOR;
    }

如您所见,我检查 Contact Separator 是否为空。这是我的模型类:

@Parcelize
class ContactItem @JvmOverloads constructor(
        var contact: Contact? = null,
        var contactSeparator: String? = null
) : Parcelable

当我们的适配器中有多个物品时,有没有更清洁的解决方案?

例如,对于联系人类型,我有一个枚举:

enum class ContactType {
    SINGLE,
    MULTIPLE
}

并将其设置在后台线程中:

if (numbers.size() > 1) {
       contact.setContactType(ContactType.MULTIPLE);
}

但是这个解决方案似乎与第一个解决方案几乎相同。你有什么建议?

源代码可以在这里找到:https://github.com/alirezaeiii/Rebtel-Contacts-Clone/tree/master

android android-adapter
1个回答
0
投票

这样的事情可以解决您的问题吗?我已经分离了“分隔符”实现

@Override
public int getItemViewType(int position) {
    ContactItem contactItem = mContacts.get(position);
    ContactType contactType = (contactItem.contact != null) ? contactItem.contact.getContactType() : ContactType.SINGLE;
    boolean hasSeparator = mShowSeparator && contactItem.contactSeparator == null;

    if (contactItem.contactSeparator != null) {
        return TYPE_SEPARATOR;
    } else if (contactType == ContactType.SINGLE && mShowSeparator) {
        return TYPE_CONTACT;
    } else if (contactType == ContactType.SINGLE) {
        return TYPE_SEARCH_CONTACT;
    } else if (!mShowSeparator && contactType != ContactType.SINGLE) {
        return TYPE_SEARCH_CONTACT_MULTIPLE;
    } else {
        return TYPE_CONTACT_MULTIPLE;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.