【发布时间】:2016-04-23 00:05:35
【问题描述】:
这是我的编码。我不知道如何验证单选按钮。当我单击下一个按钮时,即使未单击单选按钮,它仍然可以继续。对不起我的英语不好。请帮助我。谢谢。
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dengue_ques2);
radioGroup = (RadioGroup) findViewById(R.id.radioGroupDengue2);
yes2 = (RadioButton) findViewById(R.id.radioButtonQues2); //the answer is yes
no2 = (RadioButton) findViewById(R.id.radioButtonQues2No); //the answer is no
Next=(Button) findViewById(R.id.buttonNextQues2);
yes2.setSelected(true);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
if (i == R.id.radioButtonQues2)
{
selectedType = yes2.getText().toString();
}
else if (i == R.id.radioButtonQues2No)
{
selectedType = no2.getText().toString();
}
/* this part does not work
else if (i == R.id.radioButtonQues2.isChecked(false) &&
i == R.id.radioButtonQues2No.isChecked(false))
{
Toast.makeText(this, "Please choose 1 answer",
Toast.LENGTH_SHORT).show();
}*/
}
});
Next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(dengueQues2.this, dengueQues3.class);
intent.putExtra("REST2", selectedType);
startActivity(intent);
}
});
}
public void onClickYes2 (View view)
{
Toast.makeText(this, "You have select 1 to 3 days.",Toast.LENGTH_SHORT).show();
}
public void onClickNo2 (View view)
{
Toast.makeText(this, "You have select 3 to 14 days.", Toast.LENGTH_SHORT).show();
}
【问题讨论】:
-
既然你默认
yes2被选中,你不应该把selectedType默认为yes2.getText().toString()吗? -
我已经改成 yes2.getText().toString();但它仍然不起作用。
-
您的布局文件中的单选按钮是否位于单选组内?由于您的
onCreate方法中有`yes2.setSelected(true);`,因此在运行应用程序时,两个单选按钮之一应始终显示为选中状态。是这样吗? -
刚刚注意到您说您将其替换为
yes2.getText().toString()。你不想更换它,你需要两者!yes2.setSelected(true); selectedType = yes2.getText().toString(); -
是的。实际上,当我运行应用程序时,单选按钮没有默认值,即使我已将其设置为“yes2.setSelected(true)”。
标签: java android radio-button