RadioButton继承自CompoundButton.
isChecked():确定是否被选中。setChecked():强制选中或取消选中复选框。
监听器,实现OnCheckChangeListener接口,并实现回调方法onCheckedChanged().
RadioButton如果不在同一组的话,会多个选中。一组中只有一个能被选中所以我们要用RadioGroup。
我们在设置属性的时候可以在xml或者代码中设置:以默认选中为例
xml:android:checked="true"
代码:radArm.setChecked(true);
在activity_main.xml中:使用相对布局。
<RadioGroup
android:id="@+id/rgCourse"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<RadioButton
android:id="@+id/radJava"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Java"
/>
<RadioButton
android:id="@+id/radAndroid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Android"
/>
<RadioButton
android:id="@+id/radArm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="嵌入式开发"
/>
</RadioGroup>
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/rgCourse"
android:text="" />
在MainActivity中:
public class MainActivity extends AppCompatActivity {
private RadioGroup radioGroup;
private TextView textView;
private RadioButton radJava,radAndroid,radArm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radioGroup=(RadioGroup)findViewById(R.id.rgCourse);
textView=(TextView) findViewById(R.id.textView);
radJava=(RadioButton) findViewById(R.id.radJava);
radAndroid=(RadioButton) findViewById(R.id.radAndroid);
radArm=(RadioButton) findViewById(R.id.radArm);
//设置选中。(默认)。
radArm.setChecked(true);
//设置事件
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
//radioGroup 发出事件的源。 checkedId 选中单选按钮的id
@Override
public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
/* if(checkedId==radJava.getId()){
textView.setText("java");
} else if (checkedId==radAndroid.getId()){
textView.setText("android");
}else if (checkedId==radArm.getId()){
textView.setText("嵌入式开发");
}*/
/* if (radJava.isChecked()){
}else if(radAndroid.isChecked()){
}else if (radArm.isChecked()){
}*/
switch (checkedId){
case R.id.radAndroid:
textView.setText("android");
break;
case R.id.radJava:
textView.setText("java");
break;
case R.id.radArm:
textView.setText("嵌入式开发");
break;
}
}
});
}
}
以上分别使用了三种方式实现了对radioButton 的监听。