4

我在 Android 中有一个单选按钮组。我在选择项目时收到事件。目前正常。但是,如果用户单击已选择的项目,我不会收到该事件。有没有办法知道(接收事件)用户何时点击单选按钮,无论它是否被选中?非常感谢。

4

2 回答 2

4

我不明白为什么在单击已选中的单选按钮时会收到一个事件,但是如果您想通过单击取消选择单选按钮(如果它已被选中)!检查此代码它可以帮助您:

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
于 2012-05-03T23:35:16.967 回答
0

通过OnClickListener()在按钮上设置...

于 2012-05-03T23:19:50.553 回答