Using Radio Group and Radio Button


For adding a group of radio buttons to your layout file (res/layout/*.xml)

    <RadioGroup
        android:id="@+id/radioGroup1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <RadioButton
            android:id="@+id/radio0"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="One" />

        <RadioButton
            android:id="@+id/radio1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Two" />

        <RadioButton
            android:id="@+id/radio2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Three" />
    </RadioGroup>

For adding the functionality part of the Radio Group and Radio Button, copy and paste the below code in your onCreate() function of JAVA File.

Note: Below the SetContentView() line in onCreate() function.

		RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroup1);
		rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				// TODO Auto-generated method stub
				//int selection = rg.getCheckedRadioButtonId();
				RadioButton rb = (RadioButton) findViewById(checkedId);
				Toast.makeText(MainActivity.this, rb.getText() ,
						Toast.LENGTH_SHORT).show();
			}
		});

Save the changes and run your Android Application in Emulator or an Android Device. Post your comments.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s