Home > Software design >  Set Layout Params in On Create View Holder with view binding Kotlin
Set Layout Params in On Create View Holder with view binding Kotlin

Time:03-24

I always use view binding, even item view binding in recycler view adapters, but this time I want the view holder to fill 70% of the screen with some margins as well, this old way code seems fine with no view binding:

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val view = LayoutInflater.from(context).inflate(R.layout.item_task, parent, false)
        val layoutParams = LinearLayout.LayoutParams((parent.width * 0.7).toInt(), LinearLayout.LayoutParams.WRAP_CONTENT)
        layoutParams.setMargins((15.toDp()).toPx(), 0, (40.toDp()).toPx(), 0)
        view.layoutParams = layoutParams

        return MyViewHolder(view)
    }

while MyViewHolder is an inner class that returns a view holder
But if I want to use view binding it will be like this:

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
    return ViewHolder(ITEM_BINDING.inflate(LayoutInflater.from(parent.context), parent, false))
}

But in the last case I can't set layout params, It doesn't seem to have such function like setLayout Params, is there any way to set layout params with view binding or even just set margins and fill 70% percent of the width?

CodePudding user response:

Use ViewBinding.root to get view

val viewBinding = ITEM_BINDING.inflate(LayoutInflater.from(parent.context), parent, false)
val layoutParams = LinearLayout.LayoutParams((parent.width * 0.7).toInt(), LinearLayout.LayoutParams.WRAP_CONTENT)
layoutParams.setMargins((15.toDp()).toPx(), 0, (40.toDp()).toPx(), 0)

viewBinding.root.layoutParams = layoutParams

  • Related