【发布时间】:2011-03-10 03:06:59
【问题描述】:
启用或禁用复选框时接收和发送事件的正确方法是什么?
在 C# 中,我只需双击即可轻松完成所有代码。但在android中它似乎有点模糊。我想过使用触摸事件处理程序,但是如果用户有键盘,它就不会检测到更改,因为它不是触摸的。我认为android应该有一个用于复选框状态更改的本机事件。
【问题讨论】:
-
通过自己输入代码而不是点击自己的方式进行编码,并没有什么“晦涩难懂”的地方。
启用或禁用复选框时接收和发送事件的正确方法是什么?
在 C# 中,我只需双击即可轻松完成所有代码。但在android中它似乎有点模糊。我想过使用触摸事件处理程序,但是如果用户有键盘,它就不会检测到更改,因为它不是触摸的。我认为android应该有一个用于复选框状态更改的本机事件。
【问题讨论】:
CheckBox repeatChkBx = ( CheckBox ) findViewById( R.id.repeat_checkbox );
repeatChkBx.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if ( isChecked )
{
// perform logic
}
}
});
【讨论】:
由于 CheckBox(最终)扩展了 View,您可以使用标准 OnClickListener 来检测 CheckBox 何时被用户实际点击(与 ListView 更新相反):
CheckBox repeatChkBx = ( CheckBox ) findViewById( R.id.repeat_checkbox );
repeatChkBx.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if ( ((CheckBox)v).isChecked() ) {
// perform logic
}
}
});
【讨论】:
CheckBox checkbox=(CheckBox)findViewById(R.id.checkbox);
checkbox.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
if (checkbox.isChecked())
{
//Perform action when you touch on checkbox and it change to selected state
}
else
{
//Perform action when you touch on checkbox and it change to unselected state
}
}
});
【讨论】:
在 Kotlin 中:
checkBoxView.setOnCheckedChangeListener { _, isChecked ->
print("checked: $isChecked")
}
【讨论】: