activity_main.xml
<RadioGroup android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="15dp" android:id="@+id/radioGroupFruits"> <RadioButton android:text="@string/apple" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/textView" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:id="@+id/radioButtonApple" android:onClick="radioButton_onClick"/> <RadioButton android:text="@string/orange" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/radioButtonApple" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:id="@+id/radioButtonOrange" android:onClick="radioButton_onClick"/> <RadioButton android:text="@string/banana" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/radioButtonOrange" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:id="@+id/radioButtonBanana" android:onClick="radioButton_onClick"/> </RadioGroup>
MainActivity.java
TextView textViewResult; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textViewResult=(TextView) findViewById(R.id.textViewResult); } protected void radioButton_onClick(View view) { Boolean checked=((RadioButton) view).isChecked(); RadioButton selected=(RadioButton) view; switch (selected.getId()) { case R.id.radioButtonApple: if (checked) { textViewResult.setText("Apple"); } break; case R.id.radioButtonOrange: if (checked) { textViewResult.setText("Orange"); } break; case R.id.radioButtonBanana: if (checked) { textViewResult.setText("Banana"); } break; } }
References
https://www.youtube.com/watch?v=fGF6lWjJ9Os&index=14&list=PLshdtb5UWjSp0879mLeCsDQN6L73XBZTk
https://github.com/mhdr/AndroidSamples/tree/master/009