Fenil Patel
Fenil Patel

Reputation: 1546

How can I write Extension Functions in Kotlin?

I just want to convert my normal function to extension function in Kotlin.

Here is my function,

fun hideKeyboard(activity: Activity) {
  if (activity != null) {
    activity.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_SATE_HIDDEN)
    val view: View = activity.currentFocus
        if (true) run {
           val imm = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
           imm.hideSoftInputFromWindow(view.windowToken, 0)
                }
            }
        }

Upvotes: 1

Views: 2044

Answers (3)

Thakar Sahil
Thakar Sahil

Reputation: 269

Let's take an example:

How to strike a text in textview with kotlin extension?

Kotlin Extension

fun TextView.strikeTextView() {this.paintFlags = this.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG }

Calling Extension

binding.tvText.strikeTextView()

Upvotes: -1

Alok Gupta
Alok Gupta

Reputation: 1910

How to create Extension Function (Object Class) :

object ViewExtension{

 fun CustomSpinner.validate(): Boolean  {
    if(!this.isSelected){
        this.setHintTextColor(ContextCompat.getColor(this.context,android.R.color.holo_red_light))
        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 funtion

fun validateFields(): Boolean{
    var allfieldsSelected = true

    textViewDetails.validate().apply {
        if(!this)
            allfieldsSelected = false
    }
    
    priority_spinner.validate().apply {
        if(!this)
            allfieldsSelected = false
    }

 }

Also another important part is we have import the validate method before we use it :

import com.example.activities.ViewExtension.validate

Upvotes: 3

hotkey
hotkey

Reputation: 148149

You can even do that with an automatic refactoring provided by the IDE: place the cursor on the parameter that you want to convert to receiver, press Alt+Enter and select Convert parameter to receiver.

The result is:

fun Activity.hideKeyboard() {
    if (this != null) { // Note: this check is redundant, since the type is not-null
        window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_SATE_HIDDEN)
        val view: View = currentFocus
        if (true) run {
            val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(view.windowToken, 0)
        }
    }
}

Upvotes: 7

Related Questions