Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Set Layout Params in On Create View Holder with view binding Kotlin

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading