Practical No 12
Practical No 12
Q1.Write a program to show the following output.First two radio buttons are without
using radio group and next two radio buttons are using radio group.Note changes
between these two Also toast which radio button has been selected
Activity_main.xml :
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Single Radio Buttons"
android:textSize="20dp" />
<RadioButton
android:id="@+id/radioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="RadioButton 1"
android:checked="false"/>
<RadioButton
android:id="@+id/radioButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="RadioButton 2"
android:checked="false"/>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="RadioButton inside RadioGroup"
android:textSize="20dp" />
<RadioGroup
android:id="@+id/rg"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/radioButton3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Male" />
<RadioButton
android:id="@+id/radioButton4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Female" />
</RadioGroup>
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"
android:layout_marginTop="20dp"/>
</LinearLayout>
MainActivity.xml :
package com.example.radiobutton;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
RadioButton rb;
Button btn;
RadioGroup rg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = findViewById(R.id.btn);
rg = findViewById(R.id.rg);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int selected = rg.getCheckedRadioButtonId();
if (selected != -1) { // Check if a radio button is selected
rb = findViewById(selected);
Toast.makeText(getApplicationContext(), rb.getText(),
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Please select an option",
Toast.LENGTH_LONG).show();
}
}
});
}
}
Output :