radiobutton click & reclick

时间秒杀一切 提交于 2019-12-23 19:47:22

问题


I have a radio button group in Android. I receive events when the items are selected. Normal so far. But I don't get the event if the user clicks on an already selected item. Is there a way to know (to receive an event) when the users hits a radiobutton either if it is selected or not? Thanks a lot.


回答1:


i don't understand why you would get an event when clicked on an already checked radio button, but if you want to unselect a radio button by a click on it if it is already selected!! check this code it can help you:

RadioGroup radioGroup;
RadioButton radioButton1;
RadioButton radioButton2;
RadioButton radioButton3;

boolean hack = false;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    radioGroup = (RadioGroup) findViewById(R.id.rg);
    radioButton1 = (RadioButton) findViewById(R.id.r1);
    radioButton2 = (RadioButton) findViewById(R.id.r2);
    radioButton3 = (RadioButton) findViewById(R.id.r3);

    OnClickListener radioClickListener = new OnClickListener()
    {

        public void onClick(View v)
        {       //The first codition check if we have clicked on an already selected radioButton
            if (v.getId() == radioGroup.getCheckedRadioButtonId() && hack)
            {
                radioGroup.clearCheck();
            }
            else
            {
                hack = true;
            }
        }
    };

    OnCheckedChangeListener radioCheckChangeListener = new OnCheckedChangeListener()
    {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
        {
            hack = false;
        }
    };

    radioButton1.setOnCheckedChangeListener(radioCheckChangeListener);
    radioButton2.setOnCheckedChangeListener(radioCheckChangeListener);
    radioButton3.setOnCheckedChangeListener(radioCheckChangeListener);

    radioButton1.setOnClickListener(radioClickListener);
    radioButton2.setOnClickListener(radioClickListener);
    radioButton3.setOnClickListener(radioClickListener);

} 
Hope this wil help



回答2:


By setting an OnClickListener() on your buttons...



来源:https://stackoverflow.com/questions/10440386/radiobutton-click-reclick

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