Kotlin Android - How to implement CheckBox.OnCheckedChangeListener?

I am new to Kotlin. I created a snippet and implemented View.OnClickListener

and CheckBox.OnCheckedChangeListener

. View.OnClickListener

works as expected but shows an Unresloved reference for CheckBox.OnCheckedChangeListener

.

Code below

class LoginFragment : Fragment(), View.OnClickListener, CheckBox.OnCheckedChangeListener {

    override fun onClick(view: View?) {

    }


}

      

How can I implement CheckBox.OnCheckedChangeListener

..? thanks in advance

+3


source to share


3 answers


Use CheckBox.OnCheckedChangeListener like:

checkBox.setOnCheckedChangeListener { buttonView, isChecked ->
  Toast.makeText(this,isChecked.toString(),Toast.LENGTH_SHORT).show()
}

      



where checkBox

is the CheckBox identifier.

+7


source


var checkBox:CheckBox = CheckBox(context)
checkBox.setOnCheckedChangeListener { buttonView, isChecked ->  
        if (isChecked) {
                //Do Whatever you want in isChecked
        }
}

      



+1


source


CheckBox.OnClickListener

is not an existing interface. CheckBox

inherits from View

and therefore CheckBox

you can use a method setOnClickListener

that takes an instance to assign a listener View.OnClickListener

.

If you want to handle both of these events in the same way Fragment

, you have to distinguish between the CheckBox

others View

using a method parameter onClick

.

Alternatively, you can use lambdas as listeners for yours View

instead of itself Fragment

.

checkbox.setOnClickListener { view ->
    // handle clicks here
}

      

Usage setOnCheckedChangeListener

as stated in other answers is also an option with CheckBox

.

+1


source







All Articles