需求:
点击radioGroup中的radioButton,下面显示选中的radioButton的文字
代码:
myTextView1 = (TextView)findViewById(R.id.textView1);
myRadioGroup1 = (RadioGroup)findViewById(R.id.radioGroup1);
myRadio1 = (RadioButton)findViewById(R.id.radio0);
myRadio2 = (RadioButton)findViewById(R.id.radioButton1);
myTextView1.setText("");
myRadioGroup1.setOnCheckedChangeListener((OnCheckedChangeListener) mRadioChanged);
}
private RadioGroup.OnCheckedChangeListener mRadioChanged =
new RadioGroup.OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(RadioGroup arg0, int checkedId) {
// TODO Auto-generated method stub
if(checkedId == myRadio1.getId())
{
myTextView1.setText(myRadio1.getText());
}
else if(checkedId == myRadio2.getId())
{
myTextView1.setText(myRadio2.getText());
}
}
};
xml:
<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
<RadioButton
android:id="@+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="boy" />
<RadioButton
android:id="@+id/radioButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="girl" />
</RadioGroup>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/radioGroup1"
android:layout_below="@+id/radioGroup1"
android:layout_marginTop="82dp"
android:text="TextView" />
重点:
这个用法和之前的checkBox用法类似,调用的函数也一样:
setOnCheckedChangeListener
OnCheckedChangeListener
onCheckedChanged
区别在于,内部根据传进去的checkId来区分是哪个radioButton