Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

View Binding extension function

Tags:

android

kotlin

I am using the following extension function for View Binding in my adapters and in my custom views.

inline fun <T : ViewBinding> ViewGroup.viewBinding(crossinline bindingInflater: (LayoutInflater, ViewGroup, Boolean) -> T) =
 bindingInflater.invoke(LayoutInflater.from(this.context), this, true)
val binding = viewBinding(ComponentButtonBinding::inflate)

For the custom views, it works fine, but for the adapters, I need the boolean in the invoke to be false. How could I fix this and make this function work for both?

like image 902
Praveen P. Avatar asked Jun 12 '26 23:06

Praveen P.


1 Answers

You can just pass a boolean variable as well to the extension function. If you're primarily using true for it you might want to set the default value to true, but that's up to you.

inline fun <T : ViewBinding> ViewGroup.viewBinding(crossinline bindingInflater: (LayoutInflater, ViewGroup, Boolean) -> T, attachToParent: Boolean = true) =
        bindingInflater.invoke(LayoutInflater.from(this.context), this, attachToParent)

val binding = viewBinding(ComponentButtonBinding::inflate)
val binding = viewBinding(ComponentButtonBinding::inflate, false)
like image 123
Håkon Schia Avatar answered Jun 18 '26 01:06

Håkon Schia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!