有没有办法在 recyclerview 适配器 (Kotlin) 中更改 LinearLayout 宽度

Is there the way to change LinearLayout width in recyclerview adapter (Kotlin)

我有一些用 RecyclerView 生成的差异块,根据设计,最后两个块应该有另一个文本大小。我以编程方式执行此操作:

 when(position){
        0 -> {
            holder.catCard.setCardBackgroundColor(Color.parseColor("#FF5668"))
        }
        1 -> {
            holder.catCard.setCardBackgroundColor(Color.parseColor("#18C2E9"))
        }
        3 -> {
            holder.catCard.setCardBackgroundColor(Color.parseColor("#18C2E9"))
            40F.also { holder.catTitle.textSize = it }

        }
       
    }

inner class ViewHolder(itemView:View): RecyclerView.ViewHolder(itemView), View.OnClickListener{
    var catImage: ImageView = itemView.findViewById(R.id.catImage)
    var catTitle: TextView = itemView.findViewById(R.id.catTitle)
    var catCard: CardView = itemView.findViewById(R.id.catCardItem)
    var catTitleWrapper: LinearLayout = itemView.findViewById(R.id.catTitleWrapper)

    override fun onClick(viewType: View?) {
        listener.invoke(adapterPosition)
    }
}

但我还必须更改 LinearLayout 之一的视图:

var catTitleWrapper: LinearLayout = itemView.findViewById(R.id.catTitleWrapper)

来自内部 class 的变量。我尝试实施一些解决方案,但它根本不起作用。如果可能请帮我解决一下。

要更改最后一项布局参数,您必须检查列表中最后一项是否调用了 RecyclerView 方法“onBindViewHolder”,为此,在您的内部 class ViewHolder 中:

inner class ViewHolder(itemView:View): RecyclerView.ViewHolder(itemView), View.OnClickListener{
    var catImage: ImageView = itemView.findViewById(R.id.catImage)
    var catTitle: TextView = itemView.findViewById(R.id.catTitle)
    var catCard: CardView = itemView.findViewById(R.id.catCardItem)
    var catTitleWrapper: LinearLayout = itemView.findViewById(R.id.catTitleWrapper)

    if (bindingAdapterPosition+1 == itemCount) {
         val catTitleWrapperLayoutParams = catTitleWrapper.layoutparms
         catTitleWrapperLayoutParams.width = $YOUR_WIDTH: Int
    }

    override fun onClick(viewType: View?) {
        listener.invoke(adapterPosition)
    }
}

基本上,我们检查 RecyclerView 变量 bindingAdapterPosition 是否等于 itemCount,如果是,则意味着我们在最后一个项目上,然后我们继续将布局参数应用于上述包装器。 我们将 1 添加到 bindingAdapterPosition 因为它将 return 项目的索引,这意味着第一个将为 0。我手写的,如果它有效请告诉我:D