RadioButton也是单选框,不过RadioButton要和RadioGroup一起用。在RadioGroup中可以放多个RadionButton,在RadioButton中,多个框只有一个能被选。
现在来看一个例子:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RadioGroup
android:id="@+id/radio_group"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="谁最帅:"
android:textSize="20sp"/>
<RadioButton
android:id="@+id/radio_button_first"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="false"
android:text="人物1"/>
<RadioButton
android:id="@+id/radio_button_second"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="false"
android:text="人物2"/>
<RadioButton
android:id="@+id/radio_button_third"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="false"
android:text="人物3"/>
</RadioGroup>
</LinearLayout>
public class MainActivity extends AppCompatActivity {
private RadioButton radioButton1;
private RadioButton radioButton2;
private RadioButton radioButton3;
private RadioGroup radioGroup;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radioButton1 = (RadioButton) findViewById(R.id.radio_button_first);
radioButton2 = (RadioButton) findViewById(R.id.radio_button_second);
radioButton3 = (RadioButton) findViewById(R.id.radio_button_third);
radioGroup = (RadioGroup) findViewById(R.id.radio_group);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if(checkedId == radioButton1.getId()) {
display(radioButton1.getText().toString());
} else if(checkedId == radioButton2.getId()) {
display(radioButton2.getText().toString());
} else {
display(radioButton3.getText().toString());
}
}
});
}
private void display(String str) {
Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
}
}
可以通过获取RadioGroup来响应RadioButton点击效果。