Original address: http://irving-wei.iteye.com/blog/1076097
The checkbox is described in the previous section, which will be exposed to Radiogroup and RadioButton.
Their relationship is: a radiogroup corresponds to multiple RadioButton, and a RadioButton in a radiogroup can only be selected at the same time, and its selected value is the selected value of the Radiogroup.
The code for this section runs as follows:
The specific code is written as follows:
First, add the string you want to use for this program in Strings.xml:
XML code
- <? XML version= "1.0" encoding="Utf-8"?>
- <resources>
- <string name="Hello">hello world, test! </string>
- <string name="app_name">androidwithradiogroup</string>
- <string name="Radio_1"> Handsome </string>
- <string name="radio_2"> Beauty </string>
- <string name="question"> May I ask your gender? </string>
- </Resources>
The next step is to add a textview and a radiogroup that shows the information in Main.xml, which contains two RadioButton, with the following code:
XML code
- <TextView
- android:id="@+id/showtext"
- android:layout_width="228px"
- android:layout_height="49px"
- android:text="@string/question"
- android:textsize="20sp"
- />
- <!--build a radiogroup --
- <Radiogroup
- android:id="@+id/radiogroup"
- android:layout_width="137px"
- android:layout_height="216px"
- android:orientation="Horizontal"
- >
- <!--Build a RadioButton --
- <RadioButton
- android:id="@+id/radiobutton1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/radio_1"
- />
- <!--build a second RadioButton --
- <RadioButton
- android:id="@+id/radiobutton2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/radio_2"
- />
- </radiogroup>
The next step is to get the three components defined above in the subclass of activity, and then add the Oncheckedchangelistener to Radiogroup and implement the listening method.
The code is as follows:
Java code
- Super.oncreate (savedinstancestate);
- Setcontentview (R.layout.main);
- TextView = (TextView) Findviewbyid (R.id.showtext);
- Radiogroup = (radiogroup) Findviewbyid (R.id.radiogroup);
- RadioButton1 = (RadioButton) Findviewbyid (R.id.radiobutton1);
- RadioButton2 = (RadioButton) Findviewbyid (R.id.radiobutton2);
- Radiogroup.setoncheckedchangelistener (new Oncheckedchangelistener () {
- public void OnCheckedChanged (radiogroup group, int checkedid) {
- if (Checkedid = = Radiobutton1.getid ()) {
- Textview.settext (Radiobutton1.gettext ());
- } Else if (Checkedid = = Radiobutton2.getid ()) {
- Textview.settext (Radiobutton2.gettext ());
- }
- }
- });