Kotlin Android- How implement CheckBox.OnCheckedChangeListener?

前端 未结 4 1597
无人共我
无人共我 2021-01-07 16:56

I am new to Kotlin. I created a fragment and implemented View.OnClickListener and CheckBox.OnCheckedChangeListener. The View.OnClickListener

相关标签:
4条回答
  • 2021-01-07 17:22

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

    checkBox.setOnCheckedChangeListener { _, isChecked ->
       Toast.makeText(this,isChecked.toString(),Toast.LENGTH_SHORT).show()
    }
    
    0 讨论(0)
  • 2021-01-07 17:25

    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.

    0 讨论(0)
  • 2021-01-07 17:26

    Use CheckBox.OnCheckedChangeListener like:

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

    where checkBox is CheckBox ID.

    0 讨论(0)
  • 2021-01-07 17:38
    var checkBox:CheckBox = CheckBox(context)
    checkBox.setOnCheckedChangeListener { buttonView, isChecked ->  
            if (isChecked) {
                    //Do Whatever you want in isChecked
            }
    }
    
    0 讨论(0)
提交回复
热议问题