簡體   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