繁体   English   中英

在Kotlin中重构我的Viewholder类

[英]Refactor my viewholder class in kotlin

我有一个回收商列表,其中包含许多不同类型的项目视图。 使用数据绑定非常容易,而无需在视图保持器中声明布局和分配,但是我最终得到了许多双板代码,只是使用数据绑定创建了不同的视图保持器,是否有办法摆脱它们?

class ViewHolder1 private constructor(
    val binding: ViewHolder1LayoutBinding
): RecyclerView.ViewHolder(binding.root) {
    companion object {
        fun create(parent: ViewGroup): RecyclerView.ViewHolder {
            val inflater = LayoutInflater.from(parent.context)
            val binding = ViewHolder1LayoutBinding.inflate(inflater, parent, false)
            return ViewHolder1(binding)
        }
    }

    fun bind(viewModel: ViewHolder1ViewModel) {
        binding.viewModel = viewModel
        binding.executePendingBindings()
    }
}

kotlin支持视图绑定,因此无需为绑定视图做其他工作。 只需按照步骤操作,您就可以通过xml布局中定义的ID来访问视图。

在应用程序级别gradle中添加以下内容

apply plugin: 'kotlin-android-extensions'

导入视图

import kotlinx.android.synthetic.main.<layout_file>.view.*

只需检查此课程以进行演示

class NotificationHolder(itemView: View?, listener: NotificationItemListener) : RecyclerView.ViewHolder(itemView) {
    init {
        itemView?.setOnClickListener {
            listener.onNotificationItemClicked(adapterPosition)
        }
    }

    fun bind(notificationModel: NotificationModel) {
        val titleArray = notificationModel.title.split("#".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
        itemView.tvNotificationTitle.text = titleArray[0]
        itemView.tvNotificationDetails.text = notificationModel.message
        itemView.tvNotificationTime.text = notificationModel.formattedTime
        Glide.with(itemView.context).load(ServiceHandler.BASE_URL + notificationModel.icon).dontAnimate().diskCacheStrategy(DiskCacheStrategy.SOURCE).error(R.drawable.user_default_logo).into(itemView.imageView)
        if (CommonUtils.lastNotificationTime < notificationModel.date) {
            itemView.card.setCardBackgroundColor(Color.parseColor("#ffffff"))
        } else {
            itemView.card.setCardBackgroundColor(Color.parseColor("#f2f2f2"))
        }
    }
}

在适配器中,您可以覆盖

override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder {
        return if (viewType == 0 || viewType == 3) {
            NotificationHolder(LayoutInflater.from(parent?.context).inflate(R.layout.item_notification, parent, false), this)
        } else {
            NotificationListHeaderHolder(LayoutInflater.from(parent?.context).inflate(R.layout.item_notification_header, parent, false))
        }
    }

override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) {
        (holder as? NotificationHolder)?.bind(notificationList[position])
        (holder as? NotificationListHeaderHolder)?.bind(notificationList[position])

    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM