以下是我目前在OnClick
方法中使用单选按钮的代码。
switch(view.getId()) {
case R.id.op1_radio_button:
if (checked) {
score=0;
break;
}
我正在寻找if-else
版本的代码,以便使用单选按钮更容易。
答案 0 :(得分:1)
尝试一下
int id = view.getId();
if(id == R.id.op1_radio_button){
//do something
}else if(id == R.id.button2){
//do something else
}
答案 1 :(得分:0)
您应该使用RadioGroup在XML中像这样管理RadioButton选择,
<RadioGroup
android:checkedButton="@id/rbtn_male"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
android:id="@+id/rbtn_male"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Male" />
<RadioButton
android:id="@+id/rbtn_female"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Female" />
</RadioGroup>
现在,要在“活动”中管理对RadioButton的点击,请添加
RadioButton rbMale = findViewById(R.id.rbtn_male);
RadioButton rbFemale = findViewById(R.id.rbtn_female);
rbMale.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
score = 1;
}
});
rbFemale.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
score = 0;
}
});
我希望这是针对您情况的最佳答案。