如何在android复选框检查更改上接收事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3149414/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 08:55:57  来源:igfitidea点击:

How to receive a event on android checkbox check change?

androideventscheckbox

提问by Annerajb

What would be the correct way of receiving and sending an event when a check box gets enabled or disabled?

当复选框被启用或禁用时,接收和发送事件的正确方法是什么?

In C# I could just easily double click and all the code would be done for me. But in android it appears to be a bit more obscure. I thought of using the touch event handlers but then if the user has a keyboard it won't detect the change since it's not touch. I figure android should have a native event for check box state change.

在 C# 中,我可以轻松地双击,所有代码都会为我完成。但在android中它似乎有点模糊。我想过使用触摸事件处理程序,但是如果用户有键盘,它不会检测到更改,因为它不是触摸。我认为 android 应该有一个用于复选框状态更改的本机事件。

回答by Cristian

CheckBox repeatChkBx = ( CheckBox ) findViewById( R.id.repeat_checkbox );
repeatChkBx.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
    {
        if ( isChecked )
        {
            // perform logic
        }

    }
});

回答by Phileo99

Since CheckBox (eventually) extends View, you can use a standard OnClickListener to detect when the CheckBox is actually tapped by the user (as opposed to the ListView updates):

由于 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
        }
    }
});

回答by Sunil

Try this

尝试这个

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
            }
        }
    });