Introduction of Android Radio Button Control
Android provide radio control. It uses radio group feature to bind radio button into single group. So that user can select a single radio button from one group.
How to define radio control
Android use seperate file for layout. This file stored in android res/layout directory.
syntex :
How to define radio control
Android use seperate file for layout. This file stored in android res/layout directory.
syntex :
<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="Male"
android:checked="true"/>
<RadioButton
android:id="@+id/radioFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"/>
<RadioGroup/>
Above syntex define following properties
- android:id a unique id provided.
- android:layout_width this property is used to define width.
- android:layout_height this property is used to define height.
Example
- Make layout file(main.xml) which contains a checkbox. If we check on checkbox it display a message.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/linearLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <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="Male" android:checked="true"/> <RadioButton android:id="@+id/radioFemale" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Female"/> <RadioGroup/> <Button android:id="@+id/btnDisplay" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="show result" /> </LinearLayout> - Then apply onclick event
public class MyAndroidAppActivity extends Activity { private CheckBox chkandroid; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); addListenerOnButton(); } public void addListenerOnButton() { radioSexGroup = (RadioGroup) findViewById(R.id.radioSex); btnDisplay = (Button) findViewById(R.id.btnDisplay); btnDisplay.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // get selected radio button from radioGroup int selectedId = radioSexGroup.getCheckedRadioButtonId(); // find the radiobutton by returned id radioSexButton = (RadioButton) findViewById(selectedId); Toast.makeText(MyAndroidAppActivity.this, radioSexButton.getText(), Toast.LENGTH_SHORT).show(); } }); } } - Output :

This comment has been removed by the author.
ReplyDelete