这是我的编码。我不知道如何验证单选按钮。当我单击下一个按钮时,即使没有单击单选按钮,它仍然可以继续。抱歉我的英语不好。请帮帮我。谢谢。
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();
}
答案 0 :(得分:0)
您需要使用setChecked()
方法而不是单选按钮上的setSelected()
方法。
此外,您需要默认selectedType = yes2.getText().toString();
,因为您将其设置为onCreate()
中的默认选择。
yes2.setChecked(true);
selectedType = yes2.getText().toString();
EDIT显示如何使用无默认选择:
Next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(yes2.isChecked() || no2.isChecked()) {
Intent intent = new Intent(dengueQues2.this, dengueQues3.class);
intent.putExtra("REST2", selectedType);
startActivity(intent);
} else {
Toast.makeText(this, "Please choose 1 answer",
Toast.LENGTH_SHORT).show();
}
}
});