Search code examples
androidkotlinkotlin-extension

Kotlin extension function - How to make it global?


I have created a Kotlin extension function on the Android ViewGroup class so that it can do layout inflation calls easier. So, here is my extension:

fun ViewGroup.inflate(layoutRes: Int): View {
    return LayoutInflater.from(context).inflate(layoutRes, this, false)
}

and then I can use it like this in an adapter class to inflate a layout:

 override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
    val v = parent.inflate(R.layout.view_item)
    return ViewHolder(v)
}

I have declared this extension in the adapter class I am using for a RecyclerView so that it can make inflation calls easier. But I want ALL adapters or I should say all ViewGroup classes to see this extension. I want it permanent.

It seems to just stick within where I declared it not globally. Where should I declare this extension so that anytime I use a view group this method extension will be available?


Solution

  • You can make extension funtion global by declaring in object class as shown below:

    object ViewExtension{
    
     fun Spinner.validate(): Boolean  {
        if(!this.isSelected){
            this.setSpinnerHint(this.context.getString(R.string.please_select))
            return false
        }
        return true
     }
    
     fun TextInputLayout.validate(): Boolean{
        if(TextUtils.isEmpty(editText?.text)){
            this.error =  this.context.getString(R.string.required)
            return false
        }
        return true
     }
    }
    

    How to use extension funtions

    fun validateFields(): Boolean{
        var allSelected = true
    
        textInput.validate().apply {
            if(!this)
                allSelected = false
        }
        
        spinner.validate().apply {
            if(!this)
                allSelected = false
        }
    
     }
    

    Also we need to import the validate method before we use it any class :

    import com.example.ViewExtension.validate