Android 选中的单选按钮没有返回正确的值。
在我的XML布局中,我定义了3个单选按钮。第一个按钮已设置为Android 选中的单选按钮没有返回正确的值。,android,android-layout,Android,Android Layout,在我的XML布局中,我定义了3个单选按钮。第一个按钮已设置为checked=“true” 在同一个文件中,我定义了一个onRadioButtonClick()方法 public void onRadioButtonClick(View v) { boolean checked = ((RadioButton) v).isChecked(); switch(v.getId()) { case R.id.radioButton1:
checked=“true”
在同一个文件中,我定义了一个onRadioButtonClick()
方法
public void onRadioButtonClick(View v)
{
boolean checked = ((RadioButton) v).isChecked();
switch(v.getId()) {
case R.id.radioButton1:
if (checked){
MyButton = "1P";
}
break;
case R.id.radioButton2:
if (checked){
MyButton = "2P";
}
break;
case R.id.radioButton3:
if (checked){
MyButton = "3P";
}
break;
}}
public void onClick(View v) {
Log.d("LogThis", "My Print >" +MyButton);
}
最后,单击一个标准按钮(不是单选按钮),我定义了onClick()
方法
public void onRadioButtonClick(View v)
{
boolean checked = ((RadioButton) v).isChecked();
switch(v.getId()) {
case R.id.radioButton1:
if (checked){
MyButton = "1P";
}
break;
case R.id.radioButton2:
if (checked){
MyButton = "2P";
}
break;
case R.id.radioButton3:
if (checked){
MyButton = "3P";
}
break;
}}
public void onClick(View v) {
Log.d("LogThis", "My Print >" +MyButton);
}
当我单击激活onClick
方法的标准按钮时,MyButton
值打印为null
。尽管在应用程序加载时选择了radioButton1
,但仍会发生这种情况
一旦我手动选择任何其他单选按钮,这种行为就会消失。然后,MyButton
显示正确的值
有没有其他办法来解决这个问题?我哪里做错了?我假设这是因为我实现了onRadioButtonClick()
按钮中的逻辑。但我不确定采取什么替代方法来解决这个问题
PS:我无法使用
RadioGroup
,因为按钮需要与表格布局中的不同列对齐。
另一种方法是在加载视图时在代码中设置默认选中的单选按钮,同时设置MyButton
变量。例如:
rb1 = (RadioButton) findViewById(R.id.radioButton1);
rb2 = (RadioButton) findViewById(R.id.radioButton2);
rb3 = (RadioButton) findViewById(R.id.radioButton3);
rb1.setChecked(true);
MyButton = "1P";
根据需要,您需要比较RadioButton对象(通过调用它们自己的getId()
,而不是将View.getId()
与R.id.radioButtonX
e、 g
我喜欢这个简单而有效的建议:)。我想再等一段时间,看看是否有人能解释我是否在编程和/或设计上出错,只是为了能够改进我的编码:)整个事情都在
onradiobutton中单击,不单击任何单选按钮它能工作吗?如果在开关块中添加默认值框,它会工作。
rb1 = (RadioButton) findViewById(R.id.radioButton1);
switch(v.getId()) {
case (rb1.getId()) //NOT R.id.radioButton1:
if (checked){
MyButton = "1P";
}
break;