How to receive a event on android checkbox check change?

三世轮回 提交于 2019-12-28 12:09:14

问题


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.


回答1:


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

    }
});



回答2:


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 repeatChkBx = ( CheckBox ) findViewById( R.id.repeat_checkbox );
repeatChkBx.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {

        if ( ((CheckBox)v).isChecked() ) {
            // perform logic
        }
    }
});



回答3:


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


来源:https://stackoverflow.com/questions/3149414/how-to-receive-a-event-on-android-checkbox-check-change

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!