The relationship between RadioButton and Radiogroup:
1. RadioButton represents a single round radio box, while Radiogroup is a container that can hold multiple radiobutton
2, each radiogroup in the RadioButton at the same time can have only one is selected
3, different radiogroup in the RadioButton is irrelevant, that is, if there is a selection in Group A, group B can still have a selected
4. In most cases, there are at least 2 radiobutton in a radiogroup.
5, most of the occasions, a radiogroup in the RadioButton will be selected by default, and it is recommended that you put it in the start position in Radiogroup
XML layout:
1 <LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"2 Android:layout_width= "Match_parent"3 Android:layout_height= "Match_parent"4 android:orientation= "vertical">5 6 <Radiogroup7 Android:id= "@+id/group"8 Android:layout_width= "Wrap_content"9 Android:layout_height= "Wrap_content"Ten > One A - <RadioButton - Android:id= "@+id/boy" the android:checked= "true"//Set this radiobutton is selected by default - Android:layout_width= "Wrap_content" - Android:layout_height= "Wrap_content" - Android:text= "Male" /> + - <RadioButton + Android:id= "@+id/girl" A Android:layout_width= "Wrap_content" at Android:layout_height= "Wrap_content" - Android:text= "female" /> - - - </Radiogroup> - in <TextView - Android:id= "@+id/te" to Android:layout_width= "Wrap_content" + Android:layout_height= "Wrap_content" - Android:text= "Male" the /> * $ </LinearLayout>
Java code:
1 Package Com.contentprovide.liuliu.radiogroup;2 3 import android.support.annotation.IdRes;4 import android.support.v7.app.AppCompatActivity;5 import Android.os.Bundle;6 import Android.widget.RadioButton;7 import Android.widget.RadioGroup;8 import Android.widget.TextView;9 Ten Public class Mainactivity extends Appcompatactivity { One Radiogroup Group; A RadioButton check; - TextView te; - the RadioButton Boy,girl; - - @Override - protected void OnCreate (Bundle savedinstancestate) { + super.oncreate (savedinstancestate); - Setcontentview (r.layout.activity_main); + Group = (radiogroup) Findviewbyid (r.id.group); A te = (TextView) Findviewbyid (r.id.te); at - Boy = (RadioButton) Findviewbyid (r.id.boy); - girl = (RadioButton) Findviewbyid (r.id.girl); - - - in Group.setoncheckedchangelistener (New Radiogroup.oncheckedchangelistener () { - @Override to Public void OnCheckedChanged (Radiogroup radiogroup, @IdRes int i) { + //Method one - //check = (RadioButton) Findviewbyid (Radiogroup.getcheckedradiobuttonid ()); the //Te.settext (Check.gettext (). toString ()); * $ //Method twoPanax Notoginseng if (Boy.getid () ==i) { - Te.settext (Boy.gettext (). toString ()); the }else if (Girl.getid () ==i) { + Te.settext (Girl.gettext (). toString ()); A } the + - } $ }); $ - - } the}
Code is very few, the two methods are similar, pay attention to the ID name, no notes are easier to read
RadioButton of Android controls