Ruthwik
Ruthwik

Reputation: 549

Kotlin Android- How implement CheckBox.OnCheckedChangeListener?

I am new to Kotlin. I created a fragment and implemented View.OnClickListener and CheckBox.OnCheckedChangeListener. The View.OnClickListener works as expected but it shows Unresloved reference for CheckBox.OnCheckedChangeListener.

The code is below

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

    override fun onClick(view: View?) {

    }


}

How can I implement CheckBox.OnCheckedChangeListener..? Thanks in advance

Upvotes: 45

Views: 61018

Answers (5)

hangsman
hangsman

Reputation: 11

The easies way to use CheckBox.OnCheckedChangeListener for Kotlin Android like:

checkbox.setOnClickListener { view ->
if ((view as CheckBox).isChecked) {
    // Perform action when the checkbox is checked
} else {
    // Perform action when the checkbox is not checked
}
}

Hopefully this example of a code snippet can make it easier to understand the use of CheckBox.OnCheckedChangeListener

Upvotes: 1

Shalu T D
Shalu T D

Reputation: 4039

In Kotlin, you can use CheckBox.OnCheckedChangeListener like:-

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

Upvotes: 10

Siddhartha Maji
Siddhartha Maji

Reputation: 1052

Use CheckBox.OnCheckedChangeListener like:

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

where checkBox is CheckBox ID.

Upvotes: 75

zsmb13
zsmb13

Reputation: 89548

CheckBox.OnClickListener is not an existing interface. CheckBox inherits from View, and so to assign a listener to a CheckBox, you can use its setOnClickListener method, which takes an instance of View.OnClickListener.

If you want to handle both of those events in the same Fragment, you'll have to differentiate the CheckBox and the other View using the parameter of the onClick method.

Alternatively, you could use lambdas as the listeners for your Views instead of the Fragment itself.

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

Using setOnCheckedChangeListener as mentioned in the other answers is also an option with CheckBox.

Upvotes: 4

djo
djo

Reputation: 253

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

Upvotes: 17

Related Questions