【发布时间】:2012-05-29 01:43:42
【问题描述】:
我在 Android 中有一个单选按钮组。 我在选择项目时收到事件。目前正常。 但是,如果用户单击已选择的项目,我不会收到该事件。 有没有办法知道(接收事件)用户何时点击单选按钮,无论它是否被选中? 非常感谢。
【问题讨论】:
标签: android radio-button
我在 Android 中有一个单选按钮组。 我在选择项目时收到事件。目前正常。 但是,如果用户单击已选择的项目,我不会收到该事件。 有没有办法知道(接收事件)用户何时点击单选按钮,无论它是否被选中? 非常感谢。
【问题讨论】:
标签: android radio-button
我不明白为什么在单击已选中的单选按钮时会收到事件, 但是如果你想取消选择一个单选按钮,如果它已经被选中了! 检查此代码它可以帮助您:
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
【讨论】:
通过在按钮上设置OnClickListener()...
【讨论】: