I will give an example of how this is done, then you modify your code accordingly. In your xml, to add the switches, you need to define the layout as shown below -
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <RadioGroup android:id="@+id/radioSex" android:layout_width="wrap_content" android:layout_height="wrap_content" > <RadioButton android:id="@+id/radioMale" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/radio_male" android:checked="true" /> <RadioButton android:id="@+id/radioFemale" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/radio_female" /> </RadioGroup> <Button android:id="@+id/btnDisplay" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/btn_display" /> </LinearLayout>
In your Java file, do the following: i) Declare a radio group and a radio object, as shown below -
private RadioGroup radioSexGroup; private RadioButton radioSexButton; private Button btn;
ii) Register your radio unit and radio group using the xml layout as shown below -
radioSexGroup = (RadioGroup) findViewById(R.id.radioSex); btnDisplay = (Button) findViewById(R.id.btnDisplay);
iii) Add onclicklistner to the button as shown below -
btn.setOnClickListner(this);
iv) Implement the OnClickListner interface and override the unrealized methods of the OnClickListner interface
v) In the overridden OnClick method, enter the following:
int selectedId = radioSexGroup.getCheckedRadioButtonId();
And this is how it is done. Hope this helps.
source share