在kotlin中重构我的viewholder类

我有一个包含许多不同类型的项目视图的回收站列表。 使用数据绑定是很容易的,不需要在视图中声明布局和赋值,但是我最终得到了许多biloplate代码,只是用数据绑定来创建不同的视图,是否有办法摆脱它们呢?

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访问视图。

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

 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]) }